putStrLn,类型Char不匹配[Char]

时间:2010-06-04 08:43:34

标签: haskell functional-programming io

我有一个haskell问题。 putStrLn应该带一个[Char]或一个String,即使看起来我把它给了编译器,他仍然会抱怨。

*** 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返回一个String,该字符串是putStrLn的参数。那么问题是什么? :/

1 个答案:

答案 0 :(得分:11)

由于您的getS返回String而不是IO String,因此无需使用<-“提取”纯值。

只需使用

do
  let line = getS x
  putStrLn line
  getV xs

此外,您还可以<{3}}

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.

实际上,列表理解是基于列表的这个monadic属性。

cartesian xs ys = [(x, y) | x <- xs, y <- ys]
相关问题