0

I have these functions, which someone one from stackoverflow told me while trying to explain a concept, but when I tried running it, I get a lot of errors.

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

The errors are:

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.

Could somebody explain me this or fix this?

1 Answer 1

5

Function application has higher precedence than any operator, so

putStrLn "No such item - " ++ item

means

(putStrLn "No such item - ") ++ item

You need to write

putStrLn ("No such item - " ++ item)

or use the $ operator which is function application with lower precedence instead, like this:

putStrLn $ "No such item - " ++ item
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.