HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

More functional way of writing this palindrome extractor?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisextractormorewaywritingpalindromefunctional

Problem

I wrote this palindrome extractor. And even though it works, and I can solve the challenge with it, it feels very Java-like. I was wondering what adjustments I could make in order for it to be more functional.

import collection.mutable._

object Level1 {
    def palindrome(input:String) = input.reverse == input

    def extractPalindromes(input:String) = 
    {
        var counter = 0
        val palindromes = new ListBuffer[String]()
        while(counter  4).foreach(println)
    }
}

Solution

It can be as simple as:

scala> val str =  "I like racecars that go fast"
str: java.lang.String = I like racecars that go fast

scala> for { i <- 2 to str.size; s <- str.sliding(i) if s == s.reverse} yield s
res5: scala.collection.immutable.IndexedSeq[String] = Vector(cec, aceca, racecar)

Code Snippets

scala> val str =  "I like racecars that go fast"
str: java.lang.String = I like racecars that go fast

scala> for { i <- 2 to str.size; s <- str.sliding(i) if s == s.reverse} yield s
res5: scala.collection.immutable.IndexedSeq[String] = Vector(cec, aceca, racecar)

Context

StackExchange Code Review Q#5241, answer score: 12

Revisions (0)

No revisions yet.