Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applicative typeclass based on two different functors

Is there something similar to the Applicative type class, but where there are two functors for each side of the application which are different?

i.e. (<*>) :: (Functor f, Functor g) => f (a -> b) -> g a -> f b

like image 764
Jean-Baptiste Avatar asked Feb 16 '26 04:02

Jean-Baptiste


1 Answers

(Following a suggestion from @dfeuer in the comments.)

There is a construction called day convolution that lets you preserve the distinction between two functors when performing applicative operations, and delay the moment of transforming one into the other.

The Day type is simply a pair of functorial values, together with a function that combines their respective results:

data Day f g a = forall b c. Day (f b) (g c) (b -> c -> a)

Notice that the actual return values of the functors are existencialized; the return value of the composition is that of the function.

Day has advantages over other ways of combining applicative functors. Unlike Sum, the composition is still applicative. Unlike Compose, the composition is "unbiased" and doesn't impose a nesting order. Unlike Product, it lets us easily combine applicative actions with different return types, we just need to provide a suitable adapter function.

For example, here are two Day ZipList (Vec Nat2) Char values:

{-# LANGUAGE DataKinds #-}
import           Data.Functor.Day -- from "kan-extensions"
import           Data.Type.Nat -- from "fin"
import           Data.Vec.Lazy -- from "vec"
import           Control.Applicative

day1 :: Day ZipList (Vec Nat2) Char
day1 = Day (pure ()) ('b' ::: 'a' ::: VNil) (flip const)

day2 :: Day ZipList (Vec Nat2) Char
day2 = Day (ZipList "foo") (pure ()) const

(Nat2 is from the fin package, it is used to parameterize a fixed-size Vec from vec.)

We can zip them together just fine:

res :: Day ZipList (Vec Nat2) (Char,Char)
res = (,) <$> day1 <*> day2

And then transform the Vec into a ZipList and collapse the Day:

res' :: ZipList (Char,Char)
res' = dap $ trans2 (ZipList . toList) res

ghci> res'
ZipList {getZipList = [('b','f'),('a','o')]}

Using the dap and trans2 functions.

Possible performance catch: when we lift one of the functors to Day, the other is given a dummy pure () value. But this is dead weight when combining Days with (<*>). One can work smarter by wrapping the functors in Lift for transformers, to get faster operations for the simple "pure" cases.

like image 168
danidiaz Avatar answered Feb 17 '26 20:02

danidiaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!