Haskell 打印一个 return 值(Yet Another Haskell Tutorial, askForWords)

Haskell print a return value (Yet Another Haskell Tutorial, askForWords)

所以我尝试使用编译代码中的返回值将一行文本打印到终端 window。该程序如下所示:

module Main
    where

import System.IO

main = do
  askForWords

askForWords = do
  putStrLn "Pleas enter a word:"
  word <- getLine
  if word == ""
    then return []
    else do
      rest <- askForWords
      return (word ++ " " ++ rest)

当我在 GHCi 中 运行 它工作正常

*Main> main 
Pleas enter a word:
Hello
Pleas enter a word:
World
Pleas enter a word:

"Hello World "
*Main> 

当我尝试 运行 Unix 可执行文件时程序不打印最后一个字符串

% /Users/tobyone/Workspace/Haskell/yaht/Yaht ; exit;
Pleas enter a word:
Hello
Pleas enter a word:
World
Pleas enter a word:


[Process completed]

我尝试在 main 中使用 putStrLn 打印出 askForWords,但出现错误

<interactive>:2:10: error:
    Couldn't match type ‘IO [Char]’ with ‘[Char]’
    ...
    ...

您没有打印输出,您只是 returning 它。您的可执行文件有效地忽略了 main 的 return 值,它通常具有类型 IO () 来强调这一点。

module Main
    where

import System.IO

main = do
  <b>result <- </b>askForWords
  <b>putStrLn result</b>

askForWords = do
  putStrLn "Pleas enter a word:"
  word <- getLine
  if word == ""
    then return []
    else do
      rest <- askForWords
      return (word ++ " " ++ rest)

在 GHCi 中(就像大多数语言中的 REPL),表达式的值被打印到终端。

main 也可以更简单地定义为

main = askForWords >>= putStrLn