To understand the list in Haskell, the equivalent in Scala?

I read Haskell’s book, “Know Haskell for a Great Good!” Chapter 2 explains understanding the list with this small example:

boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x] 

Can someone rewrite this list comprehension in Scala, please? Does Scala have an odd or even function? Therefore i have to use

 x%2!=0 

to check if the number is odd?

Thanks in advance for the elegant solution!

Pongo

+4
source share
2 answers

Even if Scala does not have an even or odd function in its standard library (which I'm not sure about), implementing it is also trivial. Assuming this (so that it is closest to the original version of Haskell), the Scala code might look like

 val boomBangs = for { x <- xs if odd x } yield if (x < 10) "BOOM!" else "BANG!" 

Disclaimer: I still can not compile or verify it, so there are no guarantees that it works.

+11
source

As an alternative to understanding, we understand 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!) 

Relationships are actually converted to expressions withFilter , map and flatMap compiler.

+6
source

Source: https://habr.com/ru/post/1445011/


All Articles