More neatly, we can fully separate IO from computation:

    h n = interact $ show . sum . map read . take n . reverse . lines

Better yet go a small step further and make *composable* combinations of IO & pure computation, as in TV ( http://haskell.org/haskellwiki/TV).

Cheers,  - Conal

On 10/14/07, apfelmus <apfelmus@quantentunnel.de > wrote:
Brian Hurt wrote:
> I mean, contemplate this trivial exercise for a moment: write a program
> that reads from stdin a series of numbers (one number per line), and
> writes out the sum of the last n numbers.  This is a trivial problem,
> and I have no doubt that someone who knows Haskell better than I will
> reply to this email with a single line of code that does it.

Sorry, I can't resist :)

   main n = print . sum . map read . take n . reverse . lines =<<
getContents

> I'm not saying that it's impossible to go directly to Haskell, I'm
> saying that it's just very very hard.
> [&]
> I'm going to offer an opinion here that's likely to be controversial
> (in this forum): people new to functional programming shouldn't
> learn Haskell first. They should start with either Ocaml or SML first.
> If it makes it easier to accept this argument, you can consider
> Ocaml and SML as "Haskell with training wheels".

I don't agree. At least, it was different for myself.

Looking at the line of code above, I can't help it, but I perceive
Haskell as being the _simplest_ programming language in the whole world.
I had no trouble learning it (step by step from a book), maybe because
I've happily thrown away everything I (thought I) knew (about
programming). The reward was worth it.

Why do people want side effects? Purity is soo much simpler.


Regards,
apfelmus

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe