I'm new to Monads and Haskell in general and trying to understand how to return a value when using them. My code looks something like the following:
foo :: A -> B
foo a = do b <- fooC a (C 0)
-- want to return just (B "b")
fooC :: A -> C -> State MyState B
fooC a c = return (B "b")
I tried using snd (snd b)
, but apparently State MyState B
is not a tuple? How can I return the desired value (B "b")
?
Edit: Taking Daniel's advice into account, the rewrite looks like this:
data MyState = MyState String
data C = C Int
foo :: String -> String
-- want to return just "b"
foo a = evalState (fooC a) (C 0)
fooC :: String -> Int -> State MyState String
fooC a c = return "b"
That still results in a compilation error:
Couldn't match expected type `State s0 String'
with actual type `Int -> State MyState String'
In the return type of a call of `fooC'
Probable cause: `fooC' is applied to too few arguments
In the first argument of `evalState', namely `(fooC a)'
In the expression: evalState (fooC a) (C 0)
Edit 2: Fixed! Final version looks as follows:
import Control.Monad.State
data MyState = MyState String
data C = C Int
foo :: String -> String
-- want to return just (B "b")
foo a = evalState (fooC a (C 0)) (MyState "whatever")
fooC :: String -> C -> State MyState String
fooC a c = return "b"
main = print(foo("test"))
-- prints "b"