Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a list comprehension in Haskell the equivalent in Scala?

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!

like image 851
Twistleton Avatar asked Nov 09 '12 09:11

Twistleton


1 Answers

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.

like image 63
Péter Török Avatar answered Sep 28 '22 04:09

Péter Török