简体   繁体   中英

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!

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.

As an alternative to for-comprehensions, here is a solution based on filter and map :

def odd(x: Int) = x % 2 == 1

def boomBangs(xs: Seq[Int]) =
  xs filter odd map {i => if (i < 10) "BOOM!" else "BANG!"}

boomBangs(3 :: 4 :: 5 :: 10 :: 11 :: 12 :: 13 :: Nil)
  // List(BOOM!, BOOM!, BANG!, BANG!)

For-comprehensions actually get translated into withFilter , map and flatMap expressions by the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM