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)
}
@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