简体   繁体   English

Haskell如果那么“两个陈述”

[英]Haskell if then else with “two statements”

How can I do this: 我怎样才能做到这一点:

if n > 0
then putStrLn "Hello"
     putStrLn "Anything"

I want to have "two statements" in one condition but I keep getting compilation errors 我希望在一个条件中有“两个语句”,但我不断收到编译错误

I tried using semi-colon with no luck 我尝试使用分号而没有运气

then can only take one value.... But you are in luck, because do smashes multiple IO() values into one.... then只能取一个值....不过你很幸运,因为do捣毁多个IO()值转换成一个....

if n > 0
  then do
    putStrLn "Hello"
    putStrLn "Anything"
  else return ()

Remember, in Haskell, you need an else also (and return () creates the trivial IO() that does nothing). 请记住,在Haskell中,您还需要一个else (并且return ()创建无效的普通IO() )。

Your example wouldn't make sense in Haskell. 你的例子在Haskell中没有意义。 Every expression needs to have a value, which is why you always need to have an else , even if it is just return () . 每个表达式都需要有一个值,这就是为什么你总是需要有一个else ,即使它只是return ()

Because it needs to be a single expression, you can't just do 因为它需要是一个单独的表达式,所以你不能这样做

putStrLn "Hello"
putStrLn "Anything"

since those are two expressions of type IO () , which means it is a computatinon with some external effects, and that there is no result. 因为它们是IO ()类型的两个表达式,这意味着它是具有一些外部效果的计算,并且没有结果。 You have two computations that need to run in a sequence, which can be done using the >> combinator 您有两个需要在序列中运行的计算,可以使用>>组合器完成

putStrLn "Hello" >> putStrLn "Anything"

There is also an alternative syntax using the do block. 还有一种使用do块的替代语法。

do
  putStrLn "Hello"
  putStrLn "Anything"

The important thing to note here is that this will compile to the same >> code as the example above. 这里要注意的重要一点是, 这将编译为与上面示例相同的>>代码。 The do block can be thought of just as syntactic sugar (there is more to it, but for simplicity you can think of it that way.) do块可以被认为是语法糖(还有更多的东西,但为了简单起见,你可以这样想。)

Putting this all together leaves us with 把这一切放在一起就离开了我们

if n > 0
then putStrLn "Hello" >> putStrLn "Anything"
else return ()

or using the do block 或使用do块

if n > 0
then do
  putStrLn "Hello"
  putStrLn "Anything"
else return ()

Because this pattern is quite common, there is a when combinator (in Control.Monad ), which does precisely this 因为这种模式是相当普遍的,有when组合子(在Control.Monad ),其目的正是这个

when (n > 0)
  do
    putStrLn "Hello"
    putStrLn "Anything"

or just simply 或者只是简单地

when (n > 0) (putStrLn "Hello" >> putStrLn "Anything")

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

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