Skip to content

Instantly share code, notes, and snippets.

@marcosh
Last active August 17, 2020 05:49
Show Gist options
  • Save marcosh/8b697252a9e8020729f46e040ebe3248 to your computer and use it in GitHub Desktop.
Save marcosh/8b697252a9e8020729f46e040ebe3248 to your computer and use it in GitHub Desktop.
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module NamedTypeclass where
import Prelude hiding (Monoid, mempty, (<>))
data Sum
data Product
class Monoid b a where
(<>) :: a -> a -> a
mempty :: a
instance Monoid Sum Int where
x <> y = x + y
mempty = 0
instance Monoid Product Int where
x <> y = x * y
mempty = 1
instance Monoid b [a] where
x <> y = x ++ y
mempty = []
fold :: forall b a . Monoid b a => [a] -> a
fold [] = mempty @b
fold (x : xs) = (<>) @b x (fold @b xs)
sum :: [Int] -> Int
sum = fold @Sum
product :: [Int] -> Int
product = fold @Product
concat :: [[a]] -> [a]
concat = fold
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment