Created
October 12, 2019 11:20
-
-
Save thalesmg/2246b2194ed128e15a61b62391f74ae2 to your computer and use it in GitHub Desktop.
Following along with "Nicer Data Types a la Carte with DefaultSignatures"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- https://yairchu.github.io/posts/dtalc-with-defaultsigs.html | |
{-# LANGUAGE DeriveFunctor #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
{-# LANGUAGE DeriveAnyClass #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE DefaultSignatures #-} | |
{-# LANGUAGE StandaloneDeriving #-} | |
{-# LANGUAGE DerivingStrategies #-} | |
{-# LANGUAGE GeneralizedNewtypeDeriving #-} | |
{-# LANGUAGE TypeOperators #-} | |
import GHC.Generics | |
newtype Val e = Val Int deriving (Functor, Show) | |
data Add e = Add e e deriving (Functor, Show) | |
data Expr e = EVal (Val e) | EAdd (Add e) | |
deriving (Generic1, Functor, Eval) | |
class Functor f => Eval f where | |
evalAlgebra :: f Int -> Int | |
default evalAlgebra :: (Generic1 f, Eval (Rep1 f)) => f Int -> Int | |
evalAlgebra = evalAlgebra . from1 | |
deriving newtype instance Eval f => Eval (M1 i c f) | |
deriving newtype instance Eval f => Eval (Rec1 f) | |
instance (Eval f, Eval g) => Eval (f :+: g) where | |
evalAlgebra (L1 f) = evalAlgebra f | |
evalAlgebra (R1 f) = evalAlgebra f | |
instance Eval Val where | |
evalAlgebra (Val x) = x | |
instance Eval Add where | |
evalAlgebra (Add x y) = x + y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment