lopezrican304
lopezrican304

Reputation: 175

Haskell- Running monad states

I am stuck trying to get this function:

runArrayState :: Array arr => ArrayState arr e a -> arr e -> (a, arr e)

to run the ArrayState action let's call it act with array arr and get result and return the result res and original array arr' as a pair (res,arr').

ArrayState is defined as

data ArrayState arr e a = MkArrayState (arr e -> (a, arr e))

I thought it would be:

runArrayState act arr = ((act arr), arr)

or

runArrayState MkArrayState (\ arr -> (res, arr)) arr' = (res, arr')

but it all fails. Any ideas?

Upvotes: 1

Views: 194

Answers (1)

Stefan Holdermans
Stefan Holdermans

Reputation: 8050

I think

runArrayState (MkArrayState act) arr = act arr

is what you are looking for.

Your type ArrayState is defined as having a single constructor MkArrayState that has its argument a function that takes arrays to pairs consisting of a result and (presumably) an updated array. In the definition above, we use the identifier act to refer to this function and arr to the array we have as an input. At the right-hand side of the definition, we then simply apply the function act to arr to obtain the required pair.

Alternatively, you can define your type as

data ArrayState arr e a = MkArrayState {runArrayState :: arr e -> (a, arr e)}

or, (most likely) better even,

newtype ArrayState arr e a = MkArrayState {runArrayState :: arr e -> (a, arr e)}

That way, you will have directly defined a destructor function of type ArrayState arr e a -> arr e -> (a, arr e) (i.e., without the class constraint, which is not required in the version above either).

Upvotes: 3

Related Questions