我有一个haskell的问题。putStrLn应该接受一个字符或字符串,尽管我似乎把它交给了Compiler先生,但他仍然抱怨。
*** Expression : putStrLn line
*** Term : line
*** Type : Char
*** Does not match : [Char]它引用的代码是这样的:
getV::[[(Char,Float)]] -> IO ()
getV [] = putStrLn ""
getV (x:xs) = do line <- getS x
putStrLn line <-- Complaining line
getV xs
getS::[(Char,Float)] -> String
getS [] = ""
getS ((c,f):str) = do a <- "(L" ++ [c] ++")" ++ getS str
return a我确实剥离了一点,但它应该是完全相同的行为。getS返回一个字符串,该字符串是putStrLn的参数。那么问题出在哪里?:/
发布于 2010-06-04 16:46:45
由于getS返回的是String,而不是IO String,因此不需要使用<-“提取”纯值。
只需使用
do
let line = getS x
putStrLn line
getV xs此外,还有一个mapM function,您可以
getV xs = mapM (putStrLn.getS) xs而且你的getS不必要地使用了monads。
getS [] = ""
getS ((c,_):str) = "(L" ++ [c] ++ ")" ++ getS str当然,也可以只使用内置函数来编写它。
getS ps = concatMap (\(c,_) -> "(L" ++ [c] ++ ")") ps您的代码在line <- getS x行上不会失败,并且line成为Char的原因是因为List也是一个monad。例如,我们可以将笛卡尔乘积写为
cartesian :: [a] -> [b] -> [(a,b)]
cartesian xs ys = do
x <- xs -- # Now x is of type 'a', representing any element in xs
y <- ys -- # Now y is of type 'b', representing any element in ys
return (x, y) -- # Return the tuple composed of any elements in xs and ys.事实上,列表理解是基于列表的这种一元属性的。
cartesian xs ys = [(x, y) | x <- xs, y <- ys]https://stackoverflow.com/questions/2972613
复制相似问题