Semigroup with datatype containing function

I have the following datatype and an Semigroup

instance of it:

newtype Combine a b = 
  Combine { unCombine :: a -> b }

instance (Semigroup b) 
  => Semigroup (Combine a b) where 
  Combine {unCombine=f} <> Combine {unCombine=g} = Combine (f <> g)

      

What does it mean Combine (f <> g)

? I am passing to a function f

and a g

binary operator <>

, what is its result?

To understand how this works, I try to play around with the foreplay for a bit:

Prelude> let f = Combine $ \n -> Sum (n + 1)
Prelude> let g = Combine $ \n -> Sum (n - 1)
Prelude> unCombine (f <> g) $ 0
Sum {getSum = 0}

      

To me it looks like a function composition f

after g

, but I'm not sure how it works. Can anyone tell me how it works?

Another example (maybe it doesn't make sense):

*Exercises Data.Semigroup> data Zoo a b = Zoo (a -> b)
*Exercises Data.Semigroup> x = Zoo (+23)
*Exercises Data.Semigroup> :t x
x :: Num b => Zoo b b

      

How to use x

?

+3


source to share


1 answer


f <> g

calls a library instance for functions:

instance Semigroup b => Semigroup (a -> b) where
   f <> g = \x -> f x <> g x

      



So, it is defined pointwise.

Perhaps using generic newtype inference would be better here since it Combine

has exactly the same instance. You might even think if it is necessary at all Combine

.

+4


source







All Articles