Last active
August 29, 2015 14:00
-
-
Save CraZySacX/11386460 to your computer and use it in GitHub Desktop.
I think an anon function would work, but can't seem to find the proper syntax...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original.... | |
def max(xs: List[Int]): Int = { | |
def findMax(curr: Int, l: List[Int]): Int = { | |
if (l.isEmpty) | |
curr | |
else if (l.head > curr) | |
findMax(l.head, l.tail) | |
else | |
findMax(curr, l.tail) | |
} | |
} | |
// Tried to make smaller with this.... | |
def max(xs: List[Int]): Int = { | |
def findMax(curr: Int, l: List[Int]): Int = { | |
if (l.isEmpty) | |
curr | |
else | |
findMax(if (l.head > curr) l.head curr, l.tail) // <== How do I do this in Scala? | |
// Can't determine the return type | |
} | |
findMax(0, xs) | |
} |
If I make line 19
findMax({if (l.head > curr) l.head ; curr}, l.tail)
the code compiles, but does not function properly. The result is always 0.
Disregard. I just saw your comment.
And now I see why....the block was always evaluating to curr, which was initially given the value of 0 with the first call. Dur....
Also, the question required we use recursion so I wasn't able to use other methods.
Well, the pattern matching version is recursive, but I understand. :)
Or, if you wanted to be fancy, derive your own fold left. Might be an interesting exercise with types.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Even the single line syntax of if requires the else syntax. Try this on line 19...
findMax(if(l.head > cure) l.head else curr, l.tail)
However, you can improve this a lot with pattern matching...
def findMax(curr: Int, l: List[Int]): Int = l match {
case Nil => curr
case h :: t if h > curr => findMax(h, t)
case h :: t => findMax(curr, t) // this doesn't need an if guard, because match happens earlier
}
However, this is actually even more concisely expressed as a reduce...
def max(xs: List[Int]): Int = xs.foldLeft(0){ (max, x) => if(x > max) x else max }