Zimano
Zimano

Reputation: 2299

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

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?

Upvotes: 4

Views: 94

Answers (1)

Zeta
Zeta

Reputation: 105876

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

Upvotes: 10

Related Questions