Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Name collision (mapMaybe) in the Set3a exercise #12

Open
alldayalone opened this issue Nov 10, 2020 · 1 comment
Open

Name collision (mapMaybe) in the Set3a exercise #12

alldayalone opened this issue Nov 10, 2020 · 1 comment

Comments

@alldayalone
Copy link

alldayalone commented Nov 10, 2020

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)
@opqdonut
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants