Menu

Functional Programming Refresher

DEV Community: haskell·Simon Horlick·6 months ago
#fAbZL2pz
#dev#class#code#highlight#haskell
Reading 0:00
15s threshold

A Magma is a set with a (closed) binary operation.

A Semigroup is a magma where the operation is associative.

class Semigroup a where ( <> ) :: a -> a -> a -- ^ read as "append"

Must satisfy:

( x <> y ) <> z == x <> ( y <> z ) -- associativity

Example:

[ 1 , 2 ] <> [ 3 , 4 ] <> [ 5 ] == [ 1 , 2 , 3 , 4 , 5 ]

A Monoid is a semigroup with an identity element.

class Semigroup a => Monoid a where mempty :: a -- ^ identity element of <>

Must satisfy:

mempty <> x == x -- left identity x <> mempty == x -- right identity ( x <> y ) <> z == x <> ( y <> z ) -- associativity (from Semigroup)

Note: mappend is a historical name for <> and is now deprecated.

Example:

mempty <> [ 1 , 2 ] == [ 1 , 2 ] singleton 1 <> mempty == singleton 1

A Group is a monoid where every element has an inverse.

class Monoid a => Group a where invert :: a -> a -- ^ inverse of <>

Must satisfy:

x <> invert x == mempty == invert x <> x

A Functor represents a type that can be mapped over.

class Functor f where fmap :: ( a -> b )…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.