r/purescript • u/notgiorgi • Apr 21 '17
Action Monoid exercise
The Action class is a multi-parameter type class which defines an action of one type on another:
class Monoid m <= Action m a where
act :: m -> a -> aAn action is a function which describes how a monoid can be used to modify a value of another type. We expect the action to respect the concatenation operator of the monoid. For example, the monoid of natural numbers under addition (defined in the Data.Monoid.Additive module) acts on strings by repeating a string some number of times:
import Data.Monoid.Additive (Additive(..))
instance repeatAction :: Action (Additive Int) String where
act (Additive n) s = repeat n s where
repeat 0 _ = ""
repeat m s = s <> repeat (m - 1) sNote that act (Additive 2) s is equal to the combination act (Additive 1) s <> act (Additive 1) s , and Additive 1 <> Additive 1 = Additive 2 .
- Write down a reasonable set of laws which describe how the Action class should interact with the Monoid class. Hint: how do we expect mempty to act on elements? What about append ?
- Write an instance Action m a => Action m (Array a) , where the action on arrays is defined by acting on the elements independently.
I cannot figure out any of this, can somebody please explain?
In the Additive example we exactly know what monoid we are interacting with, but in case of general monoid I don't understand what to do.
View all comments
Show parent comment
4
u/paf31 Apr 23 '17
Oh, you're right of course. Sorry :) I'll correct this in the next version of the book.