Search code examples
haskellghci

When are brackets required for pattern matching?


Using this code :

-- Store a person's name, age, and favourite Thing.
data Person = Person String Int Thing
  deriving Show

brent :: Person
brent = Person "Brent" 31 SealingWax

stan :: Person
stan  = Person "Stan" 94 Cabbage

getAge :: Person -> Int
getAge (Person _ a _) = a

to access age of stan use :

getAge stan

prints : 94

Defining stan does not require brackets.

However getAge Person "a" 1 Cabbage causes error :

<interactive>:60:8:
    Couldn't match expected type `Person'
                with actual type `String -> Int -> Thing -> Person'
    Probable cause: `Person' is applied to too few arguments
    In the first argument of `getAge', namely `Person'
    In the expression: getAge Person "a" 1 Cabbage

I need to use brackets :

*Main> getAge (Person "a" 1 Cabbage)
1

Why are brackets required in this case ? But when defining stan = Person "Stan" 94 Cabbage does not require brackets ?


Solution

  • getAge Person "a" 1 Cabbage
    

    is parsed as

    (((getAge Person) "a") 1) Cabbage
    

    i.e. this would have to be a function accepting a Person-constructor and three more arguments, not a function accepting a single Person-value.

    Why it's done this way? Well, it makes multi-parameter functions much nicer. For instance, Person itself is a function, taking three arguments (the data type's fields). If Haskell didn't just feed arguments one-by-one, you would also need to write Person ("Brent", 31, Sealingwax).

    The parsing rules Haskell uses are actually much simpler than in most other languages, and they allow partial application very naturally, which is really useful. For instance,

    GHCi> map (Person "Brent" 31) [Cabbage, SealingWax]
    [Person "Brent" 31 Cabbage, Person "Brent" 31 SealingWax]