简体   繁体   English

对于 Haskell 中的列表理解,Scala 中的等价物?

[英]For a list comprehension in Haskell the equivalent in Scala?

I'm reading the Haskell book "Learn You a Haskell for Great Good!".我正在阅读 Haskell 的书“Learn You a Haskell for Great Good!”。 Chapter 2 explains list comprehension with this little example:第 2 章用这个小例子解释了列表理解:

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

Can somebody re-written this list comprehension in Scala, please?有人可以用 Scala 重写这个列表推导式吗? Scala has no even or odd function? Scala 没有偶数或奇数函数? 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.即使 Scala 在其标准库中没有evenodd函数(我不确定),实现它们也是微不足道的。 Assuming this (to keep it closest to the original Haskell version), the Scala code may look like假设这样(为了使其与原始 Haskell 版本最接近),Scala 代码可能看起来像

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 :作为 for-comprehensions 的替代方案,这里有一个基于filtermap的解决方案:

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. For-comprehensions 实际上被编译器翻译成withFiltermapflatMap表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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