这是我的代码:
mingle :: String -> String -> String
mingle (a:as) (b:bs) = ([a] ++ [b]) ++ mingle as bs
mingle [] [] = []
main = putStrLn "Enter 1st String:"
>> getLine
>>= \a -> read a >> putStrLn "Enter 2nd String:"
>> getLine
>>= \b -> read b >>= mingle a b
错误:
MingleStrings.hs:10:45:
Couldn't match type ‘[]’ with ‘IO’
Expected type: IO Char
Actual type: String
In the second argument of ‘(>>)’, namely ‘mingle a b’
In the expression: read b >> mingle a b
我的印象是,read可以将IO类型转换为标准的haskell类型。关于处理IO的其他帖子似乎都没有帮助。
答案 0 :(得分:3)
read
不会返回IO
类型,如其类型签名所示:
λ> :t read
read :: Read a => String -> a
你想要做的是:
main = putStrLn "Enter 1st String:"
>> getLine
>>= \a -> putStrLn "Enter 2nd String:"
>> getLine
>>= \b -> return $ mingle a b
由于mingle
是纯函数,因此您必须使用return
来注入IO
。另请注意,您的mingle
功能无法处理所有情况。所以你可能想解决这个问题。