Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Match(es) are Overlapped - Pattern matching on Operators

I've come across a situation where I would like to pattern match on operators. However, this throws a Pattern match(es) are overlapped error with GHC. I can't figure out why. Is pattern matching on operators not allowed? I assume that since enclosing an operator symbol in parentheses converts it into an identifier, this should have worked.

test :: (Integer -> Integer -> Integer) -> String
test (+) = "plus"
test (-) = "minus"
test _ = "other"

There are other ways I can accomplish what I want to do. I'm just curious as to why this doesn't work.

like image 239
ars-longa-vita-brevis Avatar asked Jul 15 '14 07:07

ars-longa-vita-brevis


People also ask

What are the pattern matching operators?

The pattern is a general description of the format of the string. It can consist of text or the special characters X, A, and N preceded by an integer used as a repeating factor. X stands for any characters, A stands for any alphabetic characters, and N stands for any numeric characters.

What is pattern matching technique?

Pattern matching is comparing two patterns in order to determine whether they match (i.e., that they are the same) or do not match (i.e., that they differ). Pattern matching is the core procedure of theory-testing with cases.

What is pattern matching in linguistics?

Linguistic Pattern Matching ("LPM") is a sophisticated new search technology that gives legal teams the ability to work much more quickly and thoroughly with large databases of scanned discovery documents and electronic files.

Is pattern matching faster than if else?

Conversation. Python 3.10 match statements are faster at pattern matching sequences than equivalent if-statements. MUCH faster. The second functions runs 86% faster than the first.


1 Answers

(+) and (-) are not constructors of the type Integer -> Integer -> Integer:

  • They are not constructor names
  • Integer -> Integer -> Integer is not an algebraic datatype

And so your code is equivalent to using any other variable names to bind the first argument, e.g.

test foo = "plus"
test bar = "minus"
test _   = "other"

which hopefully makes it clear that all three patterns actually match anything (and the first two bind some names). In other words, there is no way for the first pattern (foo, or (+) in your example) to fall through, which is why it overlaps with the remaining two.

like image 175
Cactus Avatar answered Nov 15 '22 08:11

Cactus