Haskell预期类型:IO Char实际类型:字符串

时间:2014-12-28 02:00:44

标签: haskell functional-programming

这是我的代码:

    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的其他帖子似乎都没有帮助。

1 个答案:

答案 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功能无法处理所有情况。所以你可能想解决这个问题。