Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning a value with a state monad
    primarykey
    data
    text
    <p>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:</p> <pre><code>foo :: A -&gt; B foo a = do b &lt;- fooC a (C 0) -- want to return just (B "b") fooC :: A -&gt; C -&gt; State MyState B fooC a c = return (B "b") </code></pre> <p>I tried using <code>snd (snd b)</code>, but apparently <code>State MyState B</code> is not a tuple? How can I return the desired value <code>(B "b")</code>?</p> <p><strong>Edit</strong>: Taking Daniel's advice into account, the rewrite looks like this:</p> <pre><code>data MyState = MyState String data C = C Int foo :: String -&gt; String -- want to return just "b" foo a = evalState (fooC a) (C 0) fooC :: String -&gt; Int -&gt; State MyState String fooC a c = return "b" </code></pre> <p>That still results in a compilation error:</p> <pre><code>Couldn't match expected type `State s0 String' with actual type `Int -&gt; 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) </code></pre> <p><strong>Edit 2</strong>: Fixed! Final version looks as follows:</p> <pre><code>import Control.Monad.State data MyState = MyState String data C = C Int foo :: String -&gt; String -- want to return just (B "b") foo a = evalState (fooC a (C 0)) (MyState "whatever") fooC :: String -&gt; C -&gt; State MyState String fooC a c = return "b" main = print(foo("test")) -- prints "b" </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload