Given a type, there is only one obvious way to implement an Additive instance, from the Linear library, to it. Conveniently, Additive has a generic implementation, so we can use deriving for it. Unfortunately, it depends on the existence of an Applicative instance, which is not derivable, so you still have to declare it:
{-# LANGUAGE DeriveGeneric, DeriveFunctor #-}
import Linear
import GHC.Generics
import Control.Applicative
data Foo a = Foo a a a deriving (Show, Functor, Generic1)
instance Additive Foo
instance Applicative Foo where
pure x = Foo x x x
Foo f g h <*> Foo x y z = Foo (f x) (g y) (h z)
main = print $ Foo 1 2 3 ^+^ Foo 4 5 6
Is there any way to derive Additive automatically, without having to declare an Applicative instance?
No.
The canonical example of a datatype which has two perfectly cromulent Applicative instances is [] / ZipList. This proves that a generic derivation of Applicative for [] would need to somehow choose one or the other, when in fact neither choice is more valid than the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With