haskellpattern-matching

Why is the function's name repeated when defining the function via pattern matching?


From Miran Lipovača's Learn you a Haskell for great good!:

lucky :: (Integral a) => a -> String  
lucky 7 = "LUCKY NUMBER SEVEN!"  
lucky x = "Sorry, you're out of luck, pal!"

In this definition of function lucky using pattern matching, why is the function's name repeated? When should I not be repeating the function's name? What is the meaning of it?


Solution

  • What you are seeing is pattern match in action.

    I will show you another example:

    test 1 = "one"
    test 2 = "two"
    test 3 = "three"
    

    Demo in ghci:

    ghci> test 1
    "one"
    ghci> test 2
    "two"
    ghci> test 3
    "three"
    ghci> test 4
    "*** Exception: Non-exhaustive patterns in function test
    

    So, when you call any function, the runtime system will try to match the input with the defined function. So a call to test 3 will initially check test 1 and since 1 is not equal to 3, it will move on to the next definition. Again since 2 is not equal to 3, it will move to the next defintion. In the next definiton since 3 is equal to 3 it will return "three" String back. When you try to pattern match something, which doesn't exist at all, the program throws the exception.