I don't know how I can make a conditional change to State Monad in Haskell. Suppose, I have a stack on State Monad.
import Control.Monad.State
push :: Int -> State [Int] ()
push x = state $ \xs -> ((), x : xs)
pop :: State [Int] Int
pop = state $ \(x : xs) -> (x, xs)
And with that, I want to write a function changing it.
someFunc :: Bool -> Int -> State [Int] ()
someFunc b x = do
let someValue = x * x
if b then
p <- pop
someValue = someValue + p
push $ someValue
For example, I want to take a bool b
and a value x
. And if b
is True
(for example, it could be a condition that my stack is not empty) I want to pop
a value from my stack and add it to some variable. Otherwise, I don't add anything to the variable and just push it into the stack.
How can I achieve this kind of behaviour?
In Haskell, every
if
needs anelse
, since everything is just a value. Also, you can't doif ... then p <- pop ...
since thedo
notation is lost in anif
statement, so you need to restart it withif ... then do p <- pop ...
.