[Haskell-cafe] loop problem

Roelof Wobben r.wobben at home.nl
Sat May 10 16:06:35 UTC 2014


Jochem Berndsen schreef op 10-5-2014 17:53:
> 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
>

Oke,

Im following this online course 
(https://www.fpcomplete.com/school/starting-with-haskell/basics-of-haskell) 
,
Maybe I have to look at a better place to learn haskell the right way 
with a lot of exercises because I learn the best if I do it a lot and 
not only read about things.

Roelof



More information about the Haskell-Cafe mailing list