Skip to content

Instantly share code, notes, and snippets.

@hanshoglund
Created October 2, 2017 10:56
Show Gist options
  • Save hanshoglund/73a96b8d28e4fb2dfcfb1a2112d2930a to your computer and use it in GitHub Desktop.
Save hanshoglund/73a96b8d28e4fb2dfcfb1a2112d2930a to your computer and use it in GitHub Desktop.
ex.hs
-- "Real world examples"
-- Ban "data"
data Foo = Foo Int a
deriving (Eq, Ord, Show, Typeable, Functor, Foldable, Traversable)
-- I can't dervive everything!
-- Solution I:
--
-- Write manually
-- Prove that instances are correct/use QuickCheck etc
-- Solution II:
-- Instead use "type" and "newtype"
-- Shortcut for
-- newtype Foo a = Foo { getFoo ... }
newtype Foo = Product (Const (Sum Int)) Identity
deriving (
-- All of the above plus
, Applicative
)
-- Steal instances from Data.Functor.*
Base language: Compose Sum Product Const Identity () Void
-- Not as generic as we would wish e.g.
Proxy a ~ Const ()
-- But only Proxy has Monad
Maybe a ~ Sum Proxy a
-- But only Maybe has Alternative
Either a b ~ Sum (Const a) (Const b)
-- But only Either has Bifunctor
-- Steal instances from mtl
data Foo a
= Foo (Int -> [a])
| Bar a
-- instances?
-- Steal instances from ekmett
data V2 = V2 a a
data V3 = V2 a a a
-- 2 ~ Bool, 3 ~ Ordering etc
-- ==>
newtype V2 a = (First 2 -> a)
deriving instance Functor V2
deriving instance Applicative V2
deriving instance Monad V2
deriving instance MonadFix V2
deriving instance Comonad V2
deriving instance Foldable V2
deriving instance Traversable V2
deriving instance Distributive V2
-- More generally for any N
-- Bad example, actually
data Bimap a b = Bimap
{ lookupA :: a -> Maybe b
, lookupB :: b -> Maybe a
}
deriving (...)
newtype Bimap a = Product (Compose ((->) a) Maybe) ((Flip (->) (Maybe a)))
newtype Bimap a = Product (Kleisli Maybe a) (Flip (Kleisli Maybe) a)
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment