在尝试使用do块内的条件时输入'if'时解析错误 [英] Parse error on input 'if' when trying to use a condition inside a do block

查看:128
本文介绍了在尝试使用do块内的条件时输入'if'时解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,我已经尝试过多种方式来编写这个代码,但是我无法使它工作。我需要的是在 do 块中使用 if 条件。

  palin :: IO()
palin
= do行< - getLine
putStr行
如果为True
然后putStr行

为了简化起见,我将条件更改为true。我尝试添加 else 这个句子,但是我得到了相同的结果。

解决方案

在Haskell中,if-else表达式并不意味着如果为true,执行foo;否则执行bar,但如果为true,则值为foo;否则,值为bar。因此,您不能忽略 else ,这与使用三元运算符( conditon? foo:bar )以其他语言显示。在你的情况下,然后部分是类型 IO()的值,所以你需要一个其他具有相同的类型。因为如果条件不成立,你不希望实际上发生antyhing,所以最直接的解决方案是使用虚拟 IO()值, return()

  palin :: IO()
palin
= < - getLine
putStr行
如果为True
则putStr行
else return()

Control.Monad 具有函数时,您也可以使用同样的效果:

$ p $ import Control.Monad

palin :: IO()
palin
= do行< - getLine
putStr行
True(putStr行)


I have the following code and I already tried multiple ways to write this, but I can't make it work. What I need is to use an if condition inside a do block.

palin :: IO ()
palin 
  = do line <- getLine
       putStr line
       if True
         then putStr line

I changed the condition to true just to make it easier. I tried adding the else sentence, but I get the same.

解决方案

In Haskell, an if-else expression does not mean "if true, execute foo; else, execute bar", but "if true, the value is foo; else, the value is bar". For that reason, you can't omit the else, much in the same way that you can't when using the ternary if operator (conditon ? foo : bar) in other languages. In your case, the then part is a value of type IO (), so you need an else with the same type. As you do not want antyhing to actually happen if the condition is false, the most immediate solution is using the dummy IO () value, return ():

palin :: IO ()
palin 
  = do line <- getLine
       putStr line
       if True
         then putStr line
         else return ()

You can also use the when function from Control.Monad, which has the same effect:

import Control.Monad

palin :: IO ()
palin 
  = do line <- getLine
       putStr line
       when True (putStr line)

这篇关于在尝试使用do块内的条件时输入'if'时解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆