[Haskell-cafe] Pattern matching on numbers?

David Menendez dave at zednenem.com
Tue Nov 18 19:00:18 EST 2008


On Tue, Nov 18, 2008 at 6:56 PM, Henning Thielemann
<lemming at henning-thielemann.de> wrote:
>
> On Tue, 18 Nov 2008, Ryan Ingram wrote:
>
>> How does this work?
>>
>>> fac n = case n of
>>>   0 -> 1
>>>   _ -> n * fac (n-1)
>>
>> ghci> :t fac
>> fac :: (Num t) => t -> t
>>
>> The first line of "fac" pattern matches on 0.  So how does this work
>> over any value of the Num typeclass?  I know that the "1" on the rhs
>> of fac are replaced with (fromInteger 1), but what about numeric
>> literals in patterns?  Does it turn into a call to (==)?
>
> As far as I know, yes. It is even possible to trap into an error on pattern
> matching this way if fromInteger generates an 'undefined'.

As I understand it, the use of (==) in numeric pattern matching is why
Num requires Eq.

-- 
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>


More information about the Haskell-Cafe mailing list