Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to derive Additive generically on Haskell, without defining an Applicative instance?

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?

like image 731
MaiaVictor Avatar asked Nov 10 '22 15:11

MaiaVictor


1 Answers

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.

like image 153
Cactus Avatar answered Dec 24 '22 02:12

Cactus