1

I can use parenthesis to make cons operator have more priority than function application in this patter match equation:

tail (_:xs) = xs

However it will be "parse error in pattern" if I try to write this:

f (g x) = 7

I see that g x produces a value and we should directly pass that value. Or in this way f g x = g x + 7 we make a call to g with an argument x in the body of f definition.

But what is the reason for not allowing to pass a function call in the pattern?

2 Answers 2

4

A pattern match is about destructuring things. Think along the lines of "I have build this data using constructor A". With pattern matching we could see what values we supplied A.

This means that means that constructors have to be invertible, we need to be able to figure out a constructors inputs given the results. Now if you wanted to do the same thing with a function call you'd be in trouble since you can't just invert a function, imagine f = const 0.

What it sounds like you want instead is a view pattern. This is where you are passed data, feed it into a function, and then pattern match on the result.

{-# LANGUAGE ViewPatterns #-}
foo (bar -> Just a) = a

This should be read as "Feed the argument to bar, then pattern match on the resulting Maybe".

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I found your explanation in the book "Real World Haskell"
Note that a good alternative to ViewPatterns can be PatternGuards, in this case foo x | Just a <- bar x = a.
2

We don't pass anything in a pattern. We describe how data that is passed must look like for the corresponding equation to take effect.

Now, it turns out that every value is of the form g x for some combination of g and x, so the pattern g x can be abbreviated to just x.

2 Comments

?? g can be any function, so the pattern cannot be abbreviated to just x in this correct version f g x = g x + 7
I think the OP had a specific g in mind, he wanted an abbreviation for applying a function to a parameter in the body. Of course g = id makes this trivial :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.