Skip to content

Name collision (mapMaybe) in the Set3a exercise #12

@alldayalone

Description

@alldayalone

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions