Newtype with Tuple

About this LearnYouaHaskell code :

newtype Pair b a = Pair {getPair :: (a,b)}
instance Functor (Pair c) where
  fmap f (Pair (x, y)) = Pair (f x, y)

      

My understanding is that the first line creates a new datatype from the tuple. However, why does the order of the arguments switch from Pair b a

to getPair :: (a,b)

? If I switch one of the orders, I get an error due to pattern matching in the definition fmap

.

+3


source to share


1 answer


The class Functor

requires one type argument, and the type requires Pair

two. Defining an instance for Pair

:

instance Functor (Pair c) where ...

      

fixes an argument of the first type that matches the second element of the tuple. This means it fmap

transforms the first element of the tuple. If the type arguments for Pair

were in a different order, you would instead convert the second element of the tuple, and the definition would have to change to:



fmap f (Pair (x, y)) = Pair (x, f y)

      

note that the inline definition for Functor

by pair already behaves this way, eg.

import Data.Functor
fmap (+1) ("first", 3)

      

+9


source







All Articles