[Haskell-cafe] loop problem
Jochem Berndsen
jochem at functor.nl
Sat May 10 15:53:44 UTC 2014
Hi Roelof,
On 05/10/2014 05:22 PM, Roelof Wobben wrote:
>
>
> Is it valid Haskell if I change the putStrln to putStrln ( show n * n)
> so I do not have to use the let command.
> Another question if I change return n with return () does the loop
> ever end. My feeling says not because the value of n is never updated
> for the loop.
>
Careful! show n * n is equal to (show n) * n, which is not what you
wanted. Function application binds very strongly in Haskell.
putStrLn (show (n*n)) is what you intended.
In Haskell, you cannot 'update' values. The loop will terminate,
however. Let's see why --
loop 101
will evaluate to
return ().
This is the action that, when performed, will do nothing.
loop 100
will evaluate to
do { putStrLn (show 100); putChar ' '; putStrLn (show (100 * 100));
loop (100 + 1) }
This is equal to
do { putStrLn (show 100); putChar ' '; putStrLn (show (100 * 100));
return () }
So `loop 100' is equal to the action that, when performed, will print
100
10000
loop 99
will evaluate to
do { putStrLn (show 99); putChar ' '; putStrLn (show (99 * 99)); loop
(99 + 1) }
which is equal to the action that, when performed, will print
99
9801
100
10000
and so on.
There is only one way to actually perform an action, which is to put it
into the definition of 'main'.
To summarize, in Haskell there is a strict separation between the
*evaluation* of values (including actions such as the above) and the
*execution* of I/O, whereas most other languages conflate the two.
For more information, see
http://www.haskell.org/haskellwiki/Introduction_to_IO
As an aside, the way this code is written is fairly unidiomatic. Haskell
programmers in general like to separate I/O if possible.
We'd generally write:
values n = [(x, x*x) | x <- [1..n]]
and then a function that writes general pairs of values.
HTH,
Jochem
--
Jochem Berndsen | jochem at functor.nl
More information about the Haskell-Cafe
mailing list