簡體   English   中英

Haskell“ \\ n”在IO字符串中顯示為字符串

[英]Haskell “\n” shown as string in IO String

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的類型是putStr String -> IO () ,您不能將其應用於imP 3 :: IO String因為putStr期望使用純String而不是IO String 這正是GHC的錯誤消息所報告的。

我以為您不熟悉monad,因此建議閱讀許多教程中的任何一個。 同時,使用\\x -> imP x >>= putStr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM