Last active
August 17, 2020 05:49
-
-
Save marcosh/8b697252a9e8020729f46e040ebe3248 to your computer and use it in GitHub Desktop.
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
{-# 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