【问题标题】:Getting putStrLn to work inside an if-else block让 putStrLn 在 if-else 块中工作
【发布时间】:2019-06-16 14:21:52
【问题描述】:

我正在用 Haskell 编写回文解决方案,我希望函数在输入 null 时显示错误。我不想使用错误功能,因为它会停止程序。因此,我想使用 putStrLn 显示错误消息并继续循环。

我曾尝试使用 show 来更改给 putStrLn 的输入,但它不起作用并引发编译时类型错误。

main = do
    putStrLn "Hey there, What's up! ENTER WORD TO CHECK PALINDROME!"
    word <- getLine
    if null word
        then
            -- putStrLn "This is not a word!"
            main    
    else do
        putStrLn  $ show  $ checkPalindrome word
        main

checkPalindrome w = if reverse w == w then True else False

我希望它显示一个错误,但它只给出一个错误。显示停止安全错误的可能解决方案是什么?

【问题讨论】:

  • I expect it to show an error, but it only gives an error. 我不明白你的意思。编译时或运行时是否出现错误?还是它运行时没有错误但做了一些意想不到的事情?

标签: haskell functional-programming


【解决方案1】:

如果您同时编写 putStrLn "this is not a word!"main,则应在此处使用 do 块:

main = do
    putStrLn "Hey there, What's up! ENTER WORD TO CHECK PALINDROME!"
    word <- getLine
    if null word
        then do
            putStrLn "This is not a word!"
            main    
    else do
        putStrLn  $ show $ checkPalindrome word
        main

话虽如此,您可以通过在maindo 块底部进行调用来简化上述操作:

main = do
    putStrLn "Hey there, What's up! ENTER WORD TO CHECK PALINDROME!"
    word <- getLine
    if null word
        then putStrLn "This is not a word!"
        else putStrLn  $ show $ checkPalindrome word
    main

或者我们可以,例如@Bergi says,甚至在main 块中添加更多内容,例如:

main = do
    putStrLn "Hey there, What's up! ENTER WORD TO CHECK PALINDROME!"
    word <- getLine
    putStrLn $ if null word
        then "This is not a word!"
        else show $ checkPalindrome word
    main

如果你在没有do 块的情况下写这个,Haskell 旨在解析putStrLn "This is not a word!" main。因此这意味着putStrLn 应该具有String -&gt; IO a -&gt; IO a 类型,但事实并非如此。

通过使用do 块,Haskell 将desugar the do block [Haskell'10 report] 转换为putStrLn "This is not a word!" &gt;&gt; main,这是合理的(至少对于类型系统而言)。由于绑定运算符的类型为(&gt;&gt;) :: Monad m =&gt; m a -&gt; m b -&gt; m b

【讨论】:

  • 太棒了!谢谢!关于为什么这部分需要单独的 do-block 的任何见解。关于函数式编程的解释会很好。
  • 您甚至可以将putStrLn 移出if
猜你喜欢
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多