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.
Ok, here you go. A state monad on top of IO, storing just your variable. Its even 'initialised' to undefined at the start :) import Control.Monad.State main = execStateT (do f1; f2; put 10) undefined f1 = do let v = 0 put v liftIO $ print v f2 = do v <- get let v' = v + 4 put v' liftIO $ print v' Running: $ runhaskell A.hs 0 4 10 Of course, there are many other ways to do this, too. -- Don _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe