Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The useful application of Functor's Product and Coproduct

Could you show a simple code example which would display the useful application of Data.Functor's Product and Coproduct?

like image 446
ais Avatar asked Dec 21 '15 12:12

ais


2 Answers

A Product of a Const and a Reader can be used to easily implement two-stage evaluation. For example, suppose you need to use some monadic effect between the two phases, but you want to make sure that your client code cannot do that (because you want to finely control how and when it happens):

type TwoPhase c r = Product (Const c) (Reader r)

run :: (Monad m, Monoid c) => (c -> m r) -> TwoPhase c r a -> m a
run prepare (Pair (Const deps, phase2)) = do
  r <- prepare deps
  return $ runReader phase2 r

Note that this of course only permits an Applicative interface for your API, not a monadic one; but that's what you usually want anyway in a situation like this.

like image 122
Cactus Avatar answered Oct 20 '22 04:10

Cactus


A possible application of coproduct functor is used in Data types a la carte. The idea is to use coproducts to combine one level up data type constructors.

like image 24
Rodrigo Ribeiro Avatar answered Oct 20 '22 02:10

Rodrigo Ribeiro