Skip to content

Instantly share code, notes, and snippets.

@tomjaguarpaw
Created January 5, 2024 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomjaguarpaw/1f4a47d1121c37fc7a911a5cf4fd3d31 to your computer and use it in GitHub Desktop.
Save tomjaguarpaw/1f4a47d1121c37fc7a911a5cf4fd3d31 to your computer and use it in GitHub Desktop.
addPoint product-profunctors
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
import Control.Applicative
import Data.Profunctor
import Data.Profunctor.Product
import Data.Profunctor.Product.Default
import Data.Profunctor.Product.Examples
import Data.Profunctor.Product.TH
data Point a = Point
{ x :: a,
y :: a
}
deriving (Functor)
$(makeAdaptorAndInstanceInferrable' ''Point)
newtype App p q a b = App {runAppExplicit :: (p -> p -> q) -> a -> a -> b}
deriving (Functor)
newtype Stop a = Stop {unStop :: a}
instance Default (App p q) (Stop p) (Stop q) where
def = App (\f (Stop a1) (Stop a2) -> Stop (f a1 a2))
runApp :: (Default (App p q) a b) => (p -> p -> q) -> a -> a -> b
runApp = runAppExplicit def
-- boilerplate (this should also be derived by Generic!)
instance Profunctor (App p q) where
lmap f (App g) = App (\t a1 a2 -> g t (f a1) (f a2))
rmap = fmap
-- boilerplate (this should also be derived by Generic!)
instance Applicative (App p q a) where
pure = App . pure . pure . pure
App f <*> App x = App (\t a1 a2 -> f t a1 a2 (x t a1 a2))
-- boilerplate (this should also be derived by Generic!)
instance ProductProfunctor (App p q) where
purePP = pure
(****) = (<*>)
zipFields :: Point a -> Point a -> (a -> a -> b) -> Point b
zipFields a b f = fmap unStop $ runApp f (fmap Stop a) (fmap Stop b)
addPoint :: (Num a) => Point a -> Point a -> Point a
addPoint a b = zipFields a b (+)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment