Newbie question on "statefullness"
Alistair Bayley
alistair@abayley.org
Mon, 12 Aug 2002 22:06:51 +0100
This has been coming up a lot, probably because of Paul Graham's challenge:
http://www.paulgraham.com/accgen.html
So the answer is probably: it has to be done this way because that's what the
challenge specifies.
Paul's language of choice is Lisp, and he combines a higher-order function
with a side-effect to give a very short and simple solution. In a side-effect
free language the answer will tend to be more cumbersome, because you have to
jump through some hoops to manage the state. This is certainly not a great
introductory problem for someone trying to learn a _pure_ functional language.
OTOH, if you want to do anything useful with any language you have to learn
to do IO (and simple IO is tackled early in most languages), and therefore
you must deal with Monads. I often wish that Haskell books and tutorials
would introduce IO earlier; it is often near the end, in the "advanced"
topics (after you've been dazzled/saturated by the magic you can do with list
functions and comprehensions, and how easy it is to create abstract
datatypes, and write parsers, etc...).
Alistair
---- Original Message: From: Andrew J Bromage Sent: Monday 12 Aug 2002 02:27
Subject: Re: Newbie question on "statefullness"
G'day all.
On Sun, Aug 11, 2002 at 05:36:21PM -0700, Alex Peake wrote:
> I am new to Haskell. I want to do something very simple (I thought)
> but got lost in the world of Monads.
>
> I want to implement something like the C idea of:
> n += i
>
> So how does one doe this in Haskell?
I think this needs to be an FAQ.
The short answer is that if you find yourself needing to do this,
especially if you're new to Haskell, you're probably thinking about
the problem in the wrong way. Haskell does not support the "n += i"
idiom in the same way that C does not support, say, higher-order
functions.
The flip side is that Haskell _does_ support the "n += i" idiom in
the same way that C _does_ support higher-order functions, in that
with some effort (sometimes a little, sometimes a lot) you can simulate
the same functionality if you find you really need it (using monads,
continuations or whatever). However, most of the time where you
would use this idiom in C, you would not use it in the equivalent
Haskell program, simply because there's usually a more appropriate
way of phrasing your intentions.
Cheers,
Andrew Bromage