Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell spitting out wrong numbers at random

Tags:

haskell

I am just starting to learn functional programming, My pick is haskell. It's been ok for a few days until something bizzare happen in the console

At first I thought the tutorial ( http://learnyouahaskell.com/starting-out ) is wrong

Prelude> [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]  
[(1,1,1)]

It should be (3,4,5) and (4,6,8). I tried 3^2+5^2, it spits out this bulks of numbers ( something like 60 rows of numbers, around 3000 digits ); 4^2+3^2 seems to produce the same numbers.

Trying to add any numbers the result will be 100

Prelude> 100 + 200
100
Prelude> 300 + 500
100

I close the window and re-open it and the problem is solved.

Does this miscalculation often happened in Haskell? or perhaps my version of Haskell is corrupted when downloading? or Any chance this is a rare bug?

like image 794
Rmxhaha Avatar asked Sep 03 '14 08:09

Rmxhaha


1 Answers

What is happening, as @BluePeppers suggested, is that you have somehow done the equivalent of let a+b = 100 in ghci, after which it uses that definition instead of the usual + in all your expressions.

You might still wonder why that gives such enormous numbers, and so did I until I realized the second point: Redefining (+) also redefines its precedence, to the default of 9 (highest). So your examples become interpreted as:

[ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]

becomes

[ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^100^2 == c^2]

and

3^2+5^2

becomes

3^100^2
like image 152
Ørjan Johansen Avatar answered Nov 15 '22 06:11

Ørjan Johansen