Reading through Learn You a Haskell , I'm trying to construct a Stack [Int] Int
:
ghci>import Control.Monad.State
ghci> let stack = state ([1,2,3]) (1) :: State [Int] Int
<interactive>:58:20:
Couldn't match expected type `s0 -> (State [Int] Int, s0)'
with actual type `[t0]'
In the first argument of `state', namely `([1, 2, 3])'
In the expression: state ([1, 2, 3]) (1) :: State [Int] Int
In an equation for `stack':
stack = state ([1, 2, 3]) (1) :: State [Int] Int
How can I create a Stack [Int] Int
?
It depends on what you're trying to do. State sa
is essentially a newtype
for a certain kind of function type (specifically s -> (a, s)
), so it doesn't really make sense to make a State
value from just a list. The simplified (internal) definition of State
looks something like
newtype State s a = State { runState :: s -> (a, s) }
Though you won't use the State
constructor directly, it does illustrate the fact that a State sa
value consists of a function.
You need a function that updates the state in some way (which could be considered a " State
action"), then you can use runState :: State sa -> s -> (a, s)
to execute the provided State
action, given a certain initial state (the s
argument).
It looks like you want to use [1, 2, 3]
as your initial state, but you do also need to provide that update function (which is what you use to construct the State sa
value itself).
In the Learn You a Haskell example, the Stack
type synonym represents the actual stack data while State Stack ...
represents a stateful action on the Stack
data. For instance, an action of type State Stack Int
uses a Stack
value as its state and results in an Int
when it is executed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.