Skip to content

Instantly share code, notes, and snippets.

@CraZySacX
Last active August 29, 2015 14:00
Show Gist options
  • Save CraZySacX/11386460 to your computer and use it in GitHub Desktop.
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...
// 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)
}
@CraZySacX
Copy link
Author

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....

@CraZySacX
Copy link
Author

Also, the question required we use recursion so I wasn't able to use other methods.

@bkyrlach
Copy link

Well, the pattern matching version is recursive, but I understand. :)

@bkyrlach
Copy link

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