I'm reading the Haskell book "Learn You a Haskell for Great Good!". Chapter 2 explains list comprehension with this little example:
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
Can somebody re-written this list comprehension in Scala, please? Scala has no even or odd function? So i must use
x%2!=0
for check if the number odd?
Thanks in advance for an elegant solution!
Even if Scala has no even
or odd
function in its standard library (which I am unsure of), it is trivial to implement either. Assuming this (to keep it closest to the original Haskell version), the Scala code may look like
val boomBangs = for {
x <- xs
if odd x
} yield if (x < 10) "BOOM!" else "BANG!"
Disclaimer: I couldn't compile or test it for the time being, so no guarantees that it works as is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With