[Haskell-cafe] Monad Imparative Usage Example

Daniel Fischer daniel.is.fischer at web.de
Wed Aug 2 07:13:54 EDT 2006


Am Mittwoch, 2. August 2006 11:56 schrieb Kaveh Shahbazian:
> 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

Well, I don't know C#, so maybe I misinterpreted Console.Write, but probably 
not, so:

import Control.Monad.State

fun1 :: StateT Int IO ()
fun1 = do put 0
          var <- get
          lift $ print var

fun2 :: StateT Int IO ()
fun2 = do modify (+4)
          var <- get
          lift $ print var

mfun :: StateT Int IO ()
mfun = do fun1
          fun2
          put 10
          var <- get
          lift $ putStrLn $ "var = " ++ show var

main :: IO ()
main = evalStateT mfun 0
          -- since the initial state isn't used, even undefined would do

Another possibility would be (using State Int (IO ()) instead of 
StateT Int IO ()):

import Control.Monad.State

fun1 = put (0::Int) >> get >>= return . print

fun2 = modify (+4) >> get >>= return . print

fin = put 10 >> get >>= return . putStrLn . (++) "var = " . show

mfun = sequence [fun1, fun2, fin]

main = sequence_ $ evalState mfun 0

but I deem the first preferable.

Also take a look at monad tutorials, e.g. Jeff Newbern's All About Monads
(sorry, I forgot the URL).

Cheers,
Daniel


-- 

"In My Egotistical Opinion, most people's C programs should be
indented six feet downward and covered with dirt."
	-- Blair P. Houghton



More information about the Haskell-Cafe mailing list