如何打印IO字符串-“无法将类型“ IO字符串”与“ [字符]”匹配预期类型:字符串实际类型:IO字符串”

时间:2019-12-21 22:30:40

标签: haskell io stdout

我希望此功能打印给定的IO String

day :: IO String -> IO ()
day p2 = do
  putStr "p2: "
  putStrLn p2

但是编译器说它需要[Char],但是据我所知它与String基本相同,所以我的问题是我如何打印IO String

这也是stack run输出的错误:

    • Couldn't match type ‘IO String’ with ‘[Char]’
      Expected type: String
        Actual type: IO String
    • In the first argument of ‘putStrLn’, namely ‘p2’
      In a stmt of a 'do' block: putStrLn p2
      In the expression: do putStrLn p2    • Couldn't match type ‘IO String’ with ‘[Char]’
      Expected type: String
        Actual type: IO String
    • In the first argument of ‘putStrLn’, namely ‘p2’
      In a stmt of a 'do' block: putStrLn p2
      In the expression: do putStrLn p2
   |
17 |   putStrLn p2
   |            ^^

我尝试做putStr ("p2: " ++ p2)并使用print,但没有成功:(

1 个答案:

答案 0 :(得分:3)

编译器的错误消息实际上非常清楚。 putStrLn的参数必须是String(或[Char],这两种类型是彼此的同义词),但是您的p2不是String但是是IO String

您说过的其他两件事都发生了相同的基本错误-他们无法解决此问题。

目前尚不清楚您想做什么。我看到两种可能性:

  • 如果只想打印出一个字符串,则根本不希望输入为IO String,而是简单的String。如果只是简单地更改类型签名,则将毫无问题地编译。

  • 也许您确实确实想输入IO String类型的动作(例如getLine)作为输入。在这种情况下,您可以使用do表示法(无论如何您已经在使用它)将操作的 output (实际为String)绑定到变量然后调用putStrLn

    day :: IO String -> IO ()
    day p2 = do
       putStr "p2: "
       s <- p2
       putStrLn s