3

This is related to the popular question of Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

For a lazy functional programming language like Haskell, how would the compiler deal with this case?

Community
  • 1
  • 1
ahala
  • 4,683
  • 5
  • 27
  • 36
  • 1
    Can you be more specific? Even with strictness analysis, it obviously cannot act as if `-ffast-math` is enabled. –  Mar 27 '14 at 13:44
  • Like nearly every compiler, GHC will do it the same way. Floating point arithmetic doesn't change from compiler to compiler. – vek Mar 27 '14 at 14:19
  • IMO, the preferrable way of writing in Haskell is `a^6`. Which will in fact be calculated via `(a*a*a)*(a*a*a)`, albeit only at runtime. Though I suppose arranging that at compile time is an optimisation GHC might well do. – leftaroundabout Mar 27 '14 at 14:50
  • 1
    For `Double` the expressions are not equivalent, so one should not be converted to the other. – augustss Mar 27 '14 at 14:54

1 Answers1

9

This isn't a difference between strict and lazy but a product of the semantics of floating point numbers.

Haskell's Double has more or less the same semantics as C's double or Java's or most other languages. Very Smart And Qualified People have met and decided what the right way to represent rational decimal numbers is in binary and we've more or less stuck to it.

So the answer is No, since rounding is independent of order of evaluation.

While here we seem to be talking about the primop GHC has for adding floating point numbers, remember that + is extensible in Haskell and just a normal function. And new instances of the Num type class have no obligation to provide associative operations.

As a simple example, I have a library which let's the user build up C AST's in a Haskell DSL. To make it convenient to add things, I added a Num instance to my library. The AST for (a + b) + c and a + (b + c) are not the same! They "slope" different ways. If GHC started randomly moving about my parens I would definitely notice and be annoyed.

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
  • To be fair, the question does not mention floating point numbers. The (*) operator may belong to `Int` or even some crazy user-defined type. – Thomas Eding Mar 29 '14 at 00:03
  • 1
    @ThomasEding It links to a question that does mention floating point numbers :) And I did address the user definedness at the bottom. – daniel gratzer Mar 29 '14 at 00:45
  • @jozefg Actually the linked question does not mention floating point numbers. However, all the answers do :p – joaerl Oct 17 '14 at 10:59