Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell pattern matching - what is it?

What is pattern matching in Haskell and how is it related to guarded equations?

I've tried looking for a simple explanation, but I haven't found one.

EDIT: Someone tagged as homework. I don't go to school anymore, I'm just learning Haskell and I'm trying to understand this concept. Pure out of interest.

like image 757
Tony The Lion Avatar asked Feb 08 '10 23:02

Tony The Lion


People also ask

What is pattern matching in programming?

Pattern matching in computer science is the checking and locating of specific sequences of data of some pattern among raw data or a sequence of tokens. Unlike pattern recognition, the match has to be exact in the case of pattern matching.

Why do we use pattern matching?

Pattern matching is used to determine whether source files of high-level languages are syntactically correct. It is also used to find and replace a matching pattern in a text or code with another text/code. Any application that supports search functionality uses pattern matching in one way or another.

What is pattern matching operator?

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 in Erlang?

Pattern matching occurs when evaluating a function call, case- receive- try- expressions and match operator (=) expressions. In a pattern matching, a left-hand side pattern is matched against a right-hand side term. If the matching succeeds, any unbound variables in the pattern become bound.


1 Answers

In a nutshell, patterns are like defining piecewise functions in math. You can specify different function bodies for different arguments using patterns. When you call a function, the appropriate body is chosen by comparing the actual arguments with the various argument patterns. Read A Gentle Introduction to Haskell for more information.

Compare:

Fibonacci sequence

with the equivalent Haskell:

fib 0 = 1 fib 1 = 1 fib n | n >= 2        = fib (n-1) + fib (n-2) 

Note the "n ≥ 2" in the piecewise function becomes a guard in the Haskell version, but the other two conditions are simply patterns. Patterns are conditions that test values and structure, such as x:xs, (x, y, z), or Just x. In a piecewise definition, conditions based on = or relations (basically, the conditions that say something "is" something else) become patterns. Guards allow for more general conditions. We could rewrite fib to use guards:

fib n | n == 0 = 1       | n == 1 = 1       | n >= 2 = fib (n-1) + fib (n-2) 
like image 120
outis Avatar answered Oct 09 '22 23:10

outis