Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, I agree with Raeez that this probably the wrong way to go, unless you really know why! If you want to increase some value by 42 (say), why not write a function that does that for you? </p> <p>It's quite a change from the traditional OO mindset where you have boxes with values in them and you take them out, manipulate them and put them back in. I would say that until you start noticing the pattern "Hey! I always take some value as an argument, and at the end return it slightly modified, tupled with some other value and all the plumbing is getting messy!" you don't really need the <code>State</code> monad. Part of the fun of (learning) Haskell is finding new ways to get around the stateful OO thinking!</p> <p>That said, if you absolutely want a box with an <code>x</code> of type <code>Int</code> in it, you could try making your own <code>get</code> and <code>put</code> variants, something like this:</p> <pre><code>import Control.Monad.State data Point = Point { x :: Int, y :: Int } deriving Show getX :: State Point Int getX = get &gt;&gt;= return . x putX :: Int -&gt; State Point () putX newVal = do pt &lt;- get put (pt { x = newVal }) increaseX :: State Point () increaseX = do x &lt;- getX putX (x + 1) test :: State Point Int test = do x1 &lt;- getX increaseX x2 &lt;- getX putX 7 x3 &lt;- getX return $ x1 + x2 + x3 </code></pre> <p>Now, if you evaluate <code>runState test (Point 2 9)</code> in ghci, you'll get back <code>(12,Point {x = 7, y = 9})</code> (since 12 = 2 + (2+1) + 7 and the <code>x</code> in the state gets set to 7 at the end). If you don't care about the returned point, you can use <code>evalState</code> and you'll get just the <code>12</code>. </p> <p>There's also more advanced things to do here like abstracting out <code>Point</code> with a typeclass in case you have multiple datastructures which have something which behaves like <code>x</code> but that's better left for another question, in my opinion!</p>
    singulars
    1. This table or related slice is empty.
    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