Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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?

like image 562
Zimano Avatar asked Dec 24 '22 10:12

Zimano


1 Answers

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
like image 180
Zeta Avatar answered May 18 '23 12:05

Zeta