1

Is this right or bug?

I read this article.

This is a very simple example of a common pattern you will see throughout Haskell. Making basic functions that are obviously correct and then combining them into more complex functions. This way you also avoid repetition. What if some mathematicians figured out that 2 is actually 3 and you had to change your program? You could just redefine doubleMe to be x + x + x and since doubleUs calls doubleMe, it would automatically work in this strange new world where 2 is 3.

When I called doubleUs 3 4 it should return 21 because I redefined the doubleMe function, but the function returned 14.

duplode
  • 33,731
  • 7
  • 79
  • 150
mrs1mple
  • 13
  • 3
  • Well in ghci, you basically each time write `let` in front of this, and thus redefine the function at every line. If you want to define a multi-line function, you need the following approach: https://stackoverflow.com/questions/2846050/how-to-define-a-function-in-ghci-across-multiple-lines – Willem Van Onsem Aug 01 '18 at 10:38
  • So yes, the definition still points to the *old* version of `doubleMe`. You can see an identifier as a way to *refer* to some object. – Willem Van Onsem Aug 01 '18 at 10:39
  • 1
    Please do not add code (or error messages, etc.) to your posts as screenshots -- paste them as text instead. – duplode Aug 01 '18 at 15:25

2 Answers2

6

The article isn't talking about having two definitions of the same function in a program where the latter overrides the former. It's talking about going into your Haskell file and replacing the old definition with the new one.

Generally you can't define two functions with same name in the same scope at all. Your code compiled in GHCi because each definition you enter into GHCi is seen as its own let statement, so it starts a new scope. So doubleUs used the old definition of doubleMe because the new one is in a different scope that doubleUs doesn't have access to (and Haskell is lexically scoped, so definitions from inner scopes don't affect functions from the outer scope). If you entered that code into a Haskell file and tried to compile it with GHC, you'd get a warning about an unreachable case because both definitions of doubleMe would be seen as a single definition with two patterns that overlap.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

you have to execute again doubleUs x y = doubleMe x + doubleMe y.

lsmor
  • 4,698
  • 17
  • 38