[Haskell-cafe] Monad Imparative Usage Example

Duncan Coutts duncan.coutts at worc.ox.ac.uk
Wed Aug 2 11:59:40 EDT 2006


On Wed, 2006-08-02 at 13:26 +0330, Kaveh Shahbazian 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.

As other people have noted, you probably don't want to to see this code
in Haskell. It's possible to translate stateful code in a 1-1 style but
that's not really the point. You'll not get much of the advantages of
the language if you do that.

You can certainly use console IO etc but for your object containing
mutable state, well in a functional style you'd simply not do that and
solve the problem in a different way.

That's why you see the code people have suggested as translations are
bigger than the code you started with, because the language is not
naturally imperative.

So the trick is to solve your problem in Haskell, not translate your
imperative solution to Haskell.

Duncan



More information about the Haskell-Cafe mailing list