Derive the Monad instance for a custom State type in Haskell without using the standard…
- User
Derive the
Monadinstance for a customStatetype in Haskell without using the standard library, explicitly definingreturnandbind. Assistant
Derive the Monad instance for a custom State type in Haskell without using the standard library, explicitly defining return and bind.
1. Understand the Goal: The user wants a Haskell implementation of the Monad instance for a custom State type. Crucially, I need to do this without using the standard library (meaning I can't just import Control.Monad.State), and I need to explicitly define return and (>>=) (bind).
Define the State Type:
State monad? It's a wrapper around a function that takes a state and returns a value and a new state.newtype State s a = State { runState :: s -> (a, s) }Understand the Functor and Applicative prerequisites:
Monad instance without first defining Functor and Applicative.fmap :: (a -> b) -> State s a -> State s b
a and state s', apply the function to a, wrap back up.pure (same as return) and (<*>).
pure: Put value into context, leave state unchanged.<*>: Extract function and value sequentially, threading state through.Derive the Monad Instance:
return (or pure):
a -> State s as -> (a, s).x. Return a function that takes a state s and returns (x, s). The state remains unchanged.return x = State $ \s -> (x, s)(>>=) (bind):
State s a -> (a -> State s b) -> State s bs -> (b, s).State s a to get the function s -> (a, s). Let's call this sa.s to sa to get the result a and the new state s'.a -> State s b (let's call it f) to the result a. This gives us a new state computation State s b. Let's call the inner function sb.s' to sb to get the final result b and final state s''.(State sa) >>= f = State $ \s ->
let (a, s') = sa s
(State sb) = f a
(b, s'') = sb s'
in (b, s'')
Structure the Explanation:
s -> (a, s)).Functor (mandatory prerequisite).Applicative (mandatory prerequisite).Monad (the core request).Drafting the Code (Mental or Scratchpad):
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f (State g) = State $ \s -> let (a, s') = g s in (f a, s')
instance Applicative (State s) where
pure x = State $ \s -> (x, s)
(State f) <*> (State g) = State $ \s ->
let (func, s') = f s
(val, s'') = g s'
in (func val, s'')
instance Monad (State s) where
return = pure
(State g) >>= h = State $ \s ->
let (a, s') = g s
(State h') = h a
in h' s'
Refining the Explanation:
return: "Keep the value, pass the state through unchanged.">>=: "Thread the state: feed input state to first action, take resulting value and new state, feed value to function to get next action, feed new state to next action."Adding the Example:
get, put, modify helper functions to make the example readable.Final Review:
return? Yes.>>=? Yes.newtype State.Construct Output: (Proceed to generate response based on these steps).
Self-Correction during drafting: The user asked specifically for the Monad instance, but modern Haskell requires Functor/Applicative. I will provide them but focus the explanation on the Monad part.
Formatting: Use code blocks, clear comments.
(Self-Correction on >>= implementation details):
Code: m >>= k = State $ \s -> let (a, s') = runState m s in runState (k a) s'
This is cleaner than manually pattern matching the State constructor if using record syntax, but pattern matching State g is often easier to read for learners. I'll stick to pattern matching State sa.
Final Polish: Ensure the helper functions (get, put) are defined to make the example runnable and understandable.
(Double check types):
return :: a -> State s a -> \s -> (a, s) looks good.
>>= :: State s a -> (a -> State s b) -> State s b -> looks good.
Let's write it out.
To derive the Monad instance for a custom State type in Haskell, we must first define the type itself. In modern Haskell (since the Applicative-Monad Proposal), you must also define Functor and Applicative instances before you can define a Monad instance.
Here is the complete implementation, starting from the type definition and building up to the Monad.
The State type is essentially a wrapper around a function that takes an initial state s and returns a result a paired with a new state s.
newtype State s a = State { runState :: s -> (a, s) }
To reach the Monad instance, we need to lay the groundwork.
Functor (fmap):
To map a function over a stateful computation, we run the computation, apply the function to the result, and return the new pair.
instance Functor (State s) where
fmap :: (a -> b) -> State s a -> State s b
fmap f (State action) = State $ \s ->
let (a, s') = action s
in (f a, s')
Applicative (pure and <*>):
pure creates a computation that simply returns a value without changing the state.
<*> applies a function wrapped in State to a value wrapped in State, threading the state through both operations sequentially.
instance Applicative (State s) where
pure :: a -> State s a
pure x = State $ \s -> (x, s)
(<*>) :: State s (a -> b) -> State s a -> State s b
(State f) <*> (State x) = State $ \s ->
let (func, s') = f s
(val, s'') = x s'
in (func val, s'')
Now we can derive the Monad instance. This requires defining return (which is identical to pure) and >>= (bind).
The Logic for Bind (>>=):
m (of type State s a) and a function k (of type a -> State s b).State s b).m using the initial state s. This gives us a result a and a new state s'.a to the function k. This gives us a second computation (State s b).s'.The Code:
instance Monad (State s) where
-- return wraps a value in the monad, leaving the state unchanged
return :: a -> State s a
return x = State $ \s -> (x, s)
-- bind chains stateful computations
(>>=) :: State s a -> (a -> State s b) -> State s b
(State action) >>= k = State $ \s ->
-- 1. Run the first computation with initial state s
let (a, s') = action s
-- 2. Apply function k to the result 'a' to get the next action
(State nextAction) = k a
-- 3. Run the next action with the updated state s'
in nextAction s'
Here is how the logic flows when you use >>=:
\s -> ... captures the initial state.action s runs the first state transformer.k a calculates the next state transformer based on the result of the first.nextAction s' runs that new transformer using the state returned by the first.Example Usage:
-- A helper to modify the state
modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)
-- A helper to get the current state
get :: State s s
get = State $ \s -> (s, s)
-- A computation: get current value, add 10, put it back
addTen :: State Int ()
addTen = do
i <- get
put (i + 10)
-- Without 'do' notation, strictly using our derived bind:
addTenManual :: State Int ()
addTenManual =
get >>= \i ->
modify (+10) >>= \_ ->
return ()