Haskell decorators

Simple and elegant as always : ( just a composition at end ) but yeah decorator to be precise by type definition
type Decoratorf a = a->a
decorate:: (Decoratorf a )->(Decoratorf a )-> (Decoratorf a)
decorate f g = f.g

data Person = Person {weight::Double,height::Double} deriving Show

weightPlus y = (\(Person w h) -> Person ( w+y) h )
heightPlus x= (\(Person w h) -> Person w (h+x) )

weightHeightDecorator x y = decorate (weightPlus x) (heightPlus y)
samplePerson::Person->Person
samplePerson = (\_->Person 20 5)

–sample runs

decorate (weightHeightDecorator 5 10) (weightHeightDecorator 5 10) (Person 30 20)
Person {weight = 40.0, height = 40.0}

decorate (weightHeightDecorator 5 10) samplePerson (Person 0 0)
Person {weight = 25.0, height = 15.0}

decorate (weightHeightDecorator 5 10) samplePerson undefined
Person {weight = 25.0, height = 15.0}

Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s