我有这些函数,stackoverflow中的某个人在尝试解释一个概念时告诉我,但是当我尝试运行它时,我遇到了很多错误。
type World = [String]
removeItem :: String -> World -> IO World
removeItem item world = do
if elem item world
then do putStrLn "Item removed."
return $ delete item world
else do putStrLn "No such item - " ++ item
return world
removeTwoItems a b world = do
world1 <- removeItem a world
world2 <- removeItem b world
return world2
look :: World -> IO World
look w = do
putStrLn $ "You see these items here: " ++ show w
return w
loop w = do
words <- fmap words getLine
case words of
("quit":_) -> return ()
("look":_) -> do w' <- look; loop w'
("remove":item:_) -> do w' <- removeItem item w; loop w'
_ -> do putStrLn "huh?"; loop w
main = do
let world0 = ["chair", "bucket"] -- the initial world
loop world0
错误是:
prac.hs:12:13:
Couldn't match expected type ‘[Char]’ with actual type ‘IO ()’
In the first argument of ‘(++)’, namely
‘putStrLn "No such item - "’
In a stmt of a 'do' block: putStrLn "No such item - " ++ item
prac.hs:12:13:
Couldn't match type ‘[]’ with ‘IO’
Expected type: IO Char
Actual type: [Char]
In a stmt of a 'do' block: putStrLn "No such item - " ++ item
In the expression:
do { putStrLn "No such item - " ++ item;
return world }
In a stmt of a 'do' block:
if elem item world then
do { putStrLn "Item removed.";
return $ delete item world }
else
do { putStrLn "No such item - " ++ item;
return world }
prac.hs:29:28:
Couldn't match expected type ‘IO World’
with actual type ‘World -> IO World’
Probable cause: ‘look’ is applied to too few arguments
In a stmt of a 'do' block: w' <- look
In the expression:
do { w' <- look;
loop w' }
Failed, modules loaded: none.
有人可以解释一下这个还是解决这个问题?
答案 0 :(得分:5)
函数应用程序的优先级高于任何运算符,因此
putStrLn "No such item - " ++ item
装置
(putStrLn "No such item - ") ++ item
你需要写
putStrLn ("No such item - " ++ item)
或使用$
运算符,它是具有较低优先级的函数应用程序
相反,像这样:
putStrLn $ "No such item - " ++ item