Why is part of my where clause not used in my conditional function?

I practiced Haskell as part of my course at my university, and I made the following function, experimenting with local definitions:

fac1 x | x == 0 = zero
       | x == 1 = one
       | otherwise = x * fac1 (x-1)
         where zero = 0
               one = 1

I expect that any call to fac1 will result in zero, because when x == 0, it will be multiplied by 0. However, it gives me the correct number.

Conversely, writing one = 0instead one = 1causes my results to be 0. I would expect the same behavior for zero, but changing its value does nothing. I feel this should happen, as I have clearly included the condition x==0. Assessment x==1, why not x==0?

Can someone explain what mistake I made?

+4
source share
1 answer

x = 1, x = 0.

fac1 2 :

fac1 2
  = 2 * fac1 (2 - 1) -- 2 is neither 0 nor 1, so we take the "otherwise" case
  = 2 * fac1 1       -- evaluate 2 - 1
  = 2 * one          -- x == 1 holds, so we return "one"
  = 2 * 1            -- one is 1
  = 2                -- done
+10

Source: https://habr.com/ru/post/1693265/


All Articles