[Haskell-cafe] Monad Imparative Usage Example

Sebastian Sylvan sylvan at student.chalmers.se
Wed Aug 2 06:22:55 EDT 2006


On 8/2/06, Kaveh Shahbazian <kaveh.shahbazian at gmail.com> wrote:
> Haskell is the most powerfull and interesting "thing" I'v ever
> encountered in IT world. But with an imparative background and lack of
> understanding (because of any thing include that maybe I am not that
> smart) has brought me problems. I know this is an old issue. But
> please help it.
> Question : Could anyone show me a sample of using a monad as a
> statefull variable?
> For example see this code in C# :
> //
> public class Test
> {
>     int var;
>     static void Fun1() { var = 0; Console.Write(var); }
>     static void Fun2() { var = var + 4; Console.Write(var); }
>     static void Main() { Fun1(); Fun2(); var = 10; Console.Write("var
> = " + var.ToString()); }
> }
> //
> I want to see this code in haskell.
> Thankyou

You're doing IO so I guess the IO monad would be the way to go here.
So something like this:


import Data.IORef

main = do var <- newIORef 0
               fun1 var
               fun2 var
               writeIORef var 10
               val <- readIORef var
               putStrLn ( "var " ++ show val)

fun1 var = do writeIORef var 0
                    val <- readIORef var
                    print val

fun2 var = do modifyIORef var (+4)
                    val <- readIORef var
                    print val

Notice that you have to pass the mutable reference around (no globals)
and extract its value explicitly whenever you want to use it.

You can also use mutable values using the ST monad rather than the IO
monad. This allows you to "run" the resulting actions from within
purely functional code, whereas there is no way to run an IO action
(i.e. you can't convert an IO Int to an Int - once you're in IO you
don't get out).

/S

-- 
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862


More information about the Haskell-Cafe mailing list