【问题标题】:Haskell "\n" shown as string in IO StringHaskell "\n" 在 IO 字符串中显示为字符串
【发布时间】:2015-11-05 18:50:49
【问题描述】:
imP:: Int -> IO String    
imP n = do
x <- getLine
if n >= 0 then return ( (concat (replicate n " ")) ++ fun1 x) else return ( fun2 n x)
where
    fun1 [] = ""
    fun1 (x:xs)
        | isAlpha x = [x] ++ fun1 xs
        | otherwise = "\n" ++ fun1 xs
    fun2 n [] = ""
    fun2 n (x:xs)
        | isAlpha x = [x] ++ fun2 n xs
        | otherwise = "\n" ++ (concat (replicate (abs n) " ")) ++ fun2 n xs

我有这个代码。并给 getLine 一个输入“hello3mello”,它返回:

"hello\nmello"

但我需要:

"hello
 mello"

编辑:

<interactive>:32:9:                                                                                                                                               
Couldn't match type `IO String' with `[Char]'                                                                                                                 
Expected type: String                                                                                                                                         
  Actual type: IO String                                                                                                                                      
In the first argument of `putStr', namely `(imP 3)'                                                                                                           
In the expression: putStr (imP 3) 

【问题讨论】:

  • 如何打印?
  • 使用 "putStr" 而不是 "print" 你会得到正确的
  • 如果你想打印出“hello mello”,请使用:putStr "\"hello\nmello\""
  • 我编辑了第一篇文章。使用 putStr 或 print 或 putStrLn 时出现该错误。

标签: string haskell io


【解决方案1】:

putStr 的类型是 String -&gt; IO (),您不能将其应用于 imP 3 :: IO String,因为 putStr 需要一个纯 String 而不是 IO String。这正是 GHC 的错误消息所报告的内容。

我假设您不熟悉 monad,因此我建议您阅读众多教程中的任何一个。同时,使用\x -&gt; imP x &gt;&gt;= putStr

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 2021-10-18
    • 2013-05-01
    • 2011-09-17
    • 1970-01-01
    • 2011-07-02
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多