I've been practicing Haskell as part of my course at my university, and I made the following function while experimenting with local definitions :
fac1 x | x == 0 = zero
| x == 1 = one
| otherwise = x * fac1 (x-1)
where zero = 0
one = 1
I would expect any call to fac1 result in zero because when x==0, it will multiply by 0. However, it gives me the correct number.
Conversely, writing one = 0
instead of one = 1
results in my results being 0. I would expect the same sort of behavior for zero, but changing the value of it does nothing. I feel like it should be happening since I clearly included a x==0
condition. The x==1
is evaluated, why not x==0
?
Can someone explain what error I made?
Your recursion stops on x = 1
, not x = 0
.
Let's evaluate fac1 2
by hand:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With