Skip to content

Instantly share code, notes, and snippets.

@horus
Created January 15, 2021 03:33
Show Gist options
  • Select an option

  • Save horus/0efc6cd422772e894df62c4307a9b8ac to your computer and use it in GitHub Desktop.

Select an option

Save horus/0efc6cd422772e894df62c4307a9b8ac to your computer and use it in GitHub Desktop.
tuple arithmetic via generics
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
module TuplePlus where
import GHC.Generics
class GTuplePlus f where
gplus :: f p -> f p -> f p
instance (Num c) => GTuplePlus (K1 i c) where
gplus (K1 x) (K1 y) = K1 (x + y)
instance GTuplePlus f => GTuplePlus (M1 i t f) where
gplus (M1 x) (M1 y) = M1 (x `gplus` y)
instance (GTuplePlus f, GTuplePlus g) => GTuplePlus (f :*: g) where
gplus (f :*: g) (f' :*: g') = (f `gplus` f') :*: (g `gplus` g')
plus :: (Generic a, GTuplePlus (Rep a)) => a -> a -> a
plus a b = to (from a `gplus` from b)
{-# SPECIALIZE plus :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int) #-}
{-# SPECIALIZE plus :: (Int, Int, Int, Int) -> (Int, Int, Int, Int) -> (Int, Int, Int, Int) #-}
{-# SPECIALIZE plus :: (Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int) #-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment