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)
答案 0 :(得分:1)
putStr
的类型为String -> IO ()
,您无法将其应用于imP 3 :: IO String
,因为putStr
期望纯String
而不是IO String
}。这正是GHC的错误消息报告的内容。
我假设你不熟悉monad,所以我建议你阅读许多教程中的任何一个。在此期间,请使用\x -> imP x >>= putStr