【问题标题】:having some trouble with user input and output in haskell在haskell中用户输入和输出有一些问题
【发布时间】:2015-01-09 18:25:34
【问题描述】:

您好,我刚开始使用haskell,但在一个涉及输入和输出的简单问题上遇到了障碍。 我试图问用户一个数学问题,在这种情况下:用户被问到将数字 37 和 53 相加的结果是什么。 如果他们输入正确答案 (90),程序将打印“优秀”,如果他们回答错误,它将打印“抱歉” 我已经设法完成了这部分。 我不明白该怎么做是然后将实际答案是什么、用户回答以及最终实际答案与用户回答之间的差异显示为输出

//the GHCI shell
it should show: 
*Main mathSkill
what is 37 + 53?
55
Sorry  
'' here is where i want it to show the rest of the info"

非常感谢任何帮助

--the haskell code
mathSkill = do
let answer = 90         
putStrLn "What is 37 + 53?"
result <- getLine
if (read result) /= answer
then putStrLn "Sorry"
else putStrLn "excellent"

【问题讨论】:

  • 那是你的实际缩进吗? Haskell 支持缩进,最好使用空格来对齐。
  • 为什么将snippets 用于javascripthtml 作为语言指示符?
  • 对不起,我找不到 Haskell 语言指示器

标签: haskell io


【解决方案1】:

@bheklilr 在这里一针见血:除了缩进之外,您的代码没有任何问题。如果你只想要一个单行,(&gt;&gt;)(&gt;&gt;=) 函数与 do-notation 做同样的事情:

Prelude> putStrLn "What is 37 + 53?" >> getLine >>= \r -> if read r /= 90 then putStrLn "Sorry" else putStrLn "Excellent"
What is 37 + 53?
30
Sorry

这相当于:

do { putStrLn "What is 37 + 53?"; r <- getLine; if read r /= 90 then putStrLn "Sorry" else putStrLn "Excellent" }

如果你省略了那些花括号和分号,Haskell 允许你做一些类似于 Python 的事情,但可以识别空格。要在 GHCi 中进行多行输入,您需要以 :{ 开头并以 :} 特殊行结束:

Prelude> :{
Prelude| do
Prelude|     putStrLn "What is 37 + 53?"
Prelude|     r <- getLine
Prelude|     if read r /= 90
Prelude|     then putStrLn "Sorry"
Prelude|     else putStrLn "Excellent"
Prelude| :}
What is 37 + 53?
50
Sorry

Haskell 会自动理解前两行应该独立存在,而 if/then/else 是一个连贯的结构。

【讨论】:

  • 问题不在于我所拥有的,而是我所没有的:一旦程序给出字符串“抱歉”,我需要显示,然后给出实际答案 90 和实际答案之间的差异答案和用户结果。也许作为一对,回答差异(90,_)
  • 啊哈。所以你需要一个字符串连接和一堆show 函数:let answer = 90 后跟guess = read r 后跟putStrLn $ "Sorry, the actual answer was: " ++ show answer ++ ", and you were off by " ++ show (abs (answer - guess)) ++ "."
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2019-03-15
  • 1970-01-01
相关资源
最近更新 更多