Home > other >  Applying some operation F to each element of a grid? - Haskell
Applying some operation F to each element of a grid? - Haskell

Time:11-07

I am new to Haskell and have some questions regarding applying a function say f to each element of a grid.

Grid Type:

data Grid a = Grid [[a]] deriving (Show, Eq)
gridG :: Grid a -> [[a]]

Function Definition:

mapGrid :: (a -> b) -> Grid a -> Grid b

How would I go about doing this? What is throwing me off is that the grid is comprised of List of Lists. Typically you can just apply the map function but throws unexpected types errors.

For example:

mapGrid :: (a -> b) -> Grid a -> Grid b
mapGrid f (Grid g) = map f g

Which throws an expected type of Grid b with actual type [b]

CodePudding user response:

You can unwrap the list of lists in a grid, and then apply map (map f) on these, so:

mapGrid :: (a -> b) -> Grid a -> Grid b
mapGrid f (Grid xs) = Grid (map (map f) xs)

Indeed the first map will map over the "rows" of your grid, and as function it will perform map f which will thus apply f on all items of the row.

You however do not need to implement such mapping yourself: by using the DeriveFunctor extension you can let Haskell implement a functor instance:

{-# LANGUAGE DeriveFunctor #-}

data Grid a = Grid [[a]] deriving (Eq, Functor, Show)

Now you can make use of fmap :: Functor f => (a -> b) -> f a -> f b. For a Grid you can thus work with fmap (1 ) (Grid [[1,4], [2,5]]) to perform f on all elements of the Grid.

  • Related