[Haskell-beginners] basic State Monad

Rein Henrichs rein.henrichs at gmail.com
Sun Dec 13 21:03:02 UTC 2015


I don't think that code snippets presented without motivation, explanation,
or commentary are an effective way to teach.

On Sun, Dec 13, 2015 at 9:14 AM Imants Cekusins <imantc at gmail.com> wrote:

> This snippet increments integer n times using state monad.
>
> How to call:
> main 10 5
>
>
>
>
> module BasicState where
>
> import Control.Monad.State.Strict
> import Debug.Trace
>
> type St a = State a a
>
>
> --  caller is not aware that main uses state
> --  mai is a pure function
> main :: Int -> Int -> Int
> main start0 repeat0 =
>         evalState (repeatN repeat0) start0
>
>
> --  state-passing computation
> repeatN :: Int -> St Int
> repeatN n0              --  repeat n times
>     | n0 < 1 = get      --  current state
>     | otherwise = do
>         withState pureStateModifier get     -- update state
>         repeatN $ n0 - 1                    --  recurse
>
>
> --  state unaware modifier function
> pureStateModifier :: Int -> Int
> pureStateModifier = (+ 1)
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20151213/18b956a9/attachment.html>


More information about the Beginners mailing list