Home > database >  Why piece-wise definition of a function in Haskell depends on the order they specified?
Why piece-wise definition of a function in Haskell depends on the order they specified?

Time:09-27

Being a beginner, I am working on an example of the function with piece-wise definition.

pts 1 = 10
pts 2 = 6
pts x = x

The code above works as I expected. However, when I tried to change the order to

pts x = x
pts 1 = 10
pts 2 = 6

I got a warning

warning: [-Woverlapping-patterns] Pattern match is redundant

and the last two statements look to be ignored by the compiler. I did not manage to Google an answer, I would be grateful for a link to the explanation.

CodePudding user response:

In Haskell, patterns in function definitions like this are checked from top to bottom. So you first example is the same as:

pts x =
  if x == 1 then 10
  else if x == 2 then 6
  else x

And your second definition is similar to:

pts x =
  if True then x
  else if x == 1 then 10
  else if x == 2 then 6
  else undefined

Clearly, in this second example the first branch is always taken, the rest are redundant.

CodePudding user response:

Haskell goes through the patterns top-to-bottom and picks the first one that matches the input. In this case, x matches any input, because it's just a plain variable, so if this is on top it is always chosen immediately and the other patterns not even considered. It's this decision:

pts x = if True then x
         else if ... -- irrelevant

If it comes at the bottom, it is only considered after the other patterns have failed, and because these match specifically only a single number, that will happen more often than not.

  • Related