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) | |
} |
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
If I make line 19
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....