haskell-mooc icon indicating copy to clipboard operation
haskell-mooc copied to clipboard

Name collision (mapMaybe) in the Set3a exercise

Open alldayalone opened this issue 4 years ago • 1 comments

When I did the last exercise (interpreter) I found it interesting to use Data.Maybe.mapMaybe. Unfortunately in the same file, in the 2nd exercise, there is a function with the same name but a different type. It took me a long time to debug type errors and resolve the collision so I suggest renaming the function or changing the exercise so the type of mapMaybe is correct.

------------------------------------------------------------------------------
-- Ex 2: implement the function mapMaybe that takes a function and a
-- Maybe value. If the value is Nothing, it returns Nothing. If it is
-- a Just, it updates the contained value using the function.
--
-- Examples:
--   mapMaybe length Nothing      ==> Nothing
--   mapMaybe length (Just "abc") ==> Just 3

mapMaybe :: (a -> b) -> Maybe a -> Maybe b
mapMaybe _ Nothing = Nothing
mapMaybe f (Just x) = Just (f x)

------------------------------------------------------------------------------
-- Ex 14: in this exercise you get to implement an interpreter for a
-- simple language. You should keep track of the x and y coordinates,
-- and interpret the following commands:

interpreter :: [String] -> [String]
interpreter cmds = Data.Maybe.mapMaybe printCoordinate (withCoordinates cmds)

printCoordinate :: (String, (Int, Int)) -> Maybe String
printCoordinate (cmd, (x,y)) = case cmd of
  "printX" -> Just (show x)
  "printY" -> Just (show y)
  "printXY" -> Just (show x ++ "," ++ show y)
  _ -> Nothing

withCoordinates :: [String] -> [(String, (Int, Int))]
withCoordinates cmds = zip cmds (scanl move (0,0) cmds)

move :: (Int, Int) -> String -> (Int, Int)
move (x,y) cmd = case cmd of
  "up"    -> (x,y+1)
  "down"  -> (x,y-1)
  "right" -> (x+1,y)
  "left"  -> (x-1,y)
  _       -> (x,y)

alldayalone avatar Nov 10 '20 20:11 alldayalone

yeah that's a good point. we'll change the exercise when we do a bigger update for the course – changing the name of the function to define will break people's answers so I don't want to do it right now

opqdonut avatar Nov 23 '20 17:11 opqdonut