We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
For Scala folks: there are different ways to terminate the recursion/fold early (to return false immediately upon seeing the first vioation).
If you are new to FP try doing it yourslef with recursion.
Another way is using a return keyword in the foldLeft . Although it's not 100% functional to do that (kind of cheating), it seems to be acceptable.
Another way is to use lazy data structures such as Stream. Look at .toStream on collections (Seq, or Array) and .scanLeft (similar to foldLeft but keeps intermediate results), and finally either exists or forall for early termination.
Another way (used in other FP languages such as Erlang) is to use exceptions, but it's not the best idea to do so in JVM.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Functions or Not?
You are viewing a single comment's thread. Return to all comments →
For Scala folks: there are different ways to terminate the recursion/fold early (to return false immediately upon seeing the first vioation).
If you are new to FP try doing it yourslef with recursion.
Another way is using a
return
keyword in thefoldLeft
. Although it's not 100% functional to do that (kind of cheating), it seems to be acceptable.Another way is to use lazy data structures such as
Stream
. Look at.toStream
on collections (Seq
, orArray
) and.scanLeft
(similar tofoldLeft
but keeps intermediate results), and finally eitherexists
orforall
for early termination.Another way (used in other FP languages such as Erlang) is to use exceptions, but it's not the best idea to do so in JVM.