[英]putStrLn, type Char does not match [Char]
I have an haskell problem. 我有一个haskell问题。 putStrLn is supposed to take a [Char], or a String, and even though it seems like I give that to mr Compiler, he still complains.
putStrLn应该采用[Char]或String格式,即使似乎我将其交给Compiler先生,他仍然抱怨。
*** Expression : putStrLn line
*** Term : line
*** Type : Char
*** Does not match : [Char]
The code that it refers to is this: 它引用的代码是这样的:
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
I did strip it a little bit, but it should be exactly the same behaviour. 我确实删除了一点,但是应该是完全相同的行为。 getS do return a String and that string is the argument for putStrLn.
getS返回一个字符串,该字符串是putStrLn的参数。 So what is the problem?
那是什么问题呢? :/
:/
Since your getS
returns a String
, not an IO String
, there's no need to "extract" the pure value with <-
. 由于您的
getS
返回的是String
而不是IO String
,因此无需使用<-
来“提取”纯值。
Just use 只需使用
do
let line = getS x
putStrLn line
getV xs
Also, there's a mapM
function which you can 此外,还有一个
mapM
函数 ,您可以
getV xs = mapM (putStrLn.getS) xs
and your getS
is using monads unnecessarily. 并且您的
getS
不必要地使用了monad。
getS [] = ""
getS ((c,_):str) = "(L" ++ [c] ++ ")" ++ getS str
Of course, it's possible to write it using built-in functions only. 当然,可以仅使用内置函数来编写它。
getS ps = concatMap (\(c,_) -> "(L" ++ [c] ++ ")") ps
The reason your code doesn't fail on the line <- getS x
line, and line
becomes a Char
is because List is also a monad. 您的代码不会在
line <- getS x
行上失败并且该line
成为Char
的原因是因为List也是monad。 For instance, we can write the Cartesian product as 例如,我们可以将笛卡尔乘积写为
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.
In fact, list comprehension is based on this monadic property of list. 实际上,列表理解是基于列表的这种单子属性。
cartesian xs ys = [(x, y) | x <- xs, y <- ys]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.