Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a nested pattern in Haskell?

What is a 'nested' pattern in Haskell. I hear the term everywhere but am not sure what the it actually means. How would you define it? Any examples?

Thanks in advance.

EDITED TO ADD: (as quoted in textbook on request)

"Patterns can contain literals and nested patterns, as in the examples:

addPair (0,y) = y

addPair (x,y) = x+y


shift :: ((Int,Int),Int) -> (Int,(Int,Int))

shift ((x,y),z) = (x,(y,z))
like image 990
maclunian Avatar asked May 08 '11 10:05

maclunian


People also ask

What is a nested pattern?

A nested pattern is a pattern that contains other non-trivial patterns (where by "non-trivial" I mean "not a variable or wildcard pattern").

What is a pattern in Haskell?

We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.

What does pattern matching mean in Haskell?

Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.

What is pattern matching explain with example?

Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.


1 Answers

This means that you can match against a pattern that contains another pattern. In your example, the (x, y) pattern is contained inside the larger ((x, y), z) pattern. The nesting can be arbitrarily deep, e.g. all of the following are legal:

f    ((x2,x0),x1)                 = ()
f'   (((x3, x2),x0),x1)           = ()
f''  ((((x4,x3), x2),x0),x1)      = ()
f''' (((((x5,x4),x3), x2),x0),x1) = ()

and so on. This also extends to lists and algebraic datatypes:

f  [[x]]   = ()
f' [[[x]]] = ()

g  (Just (Just x))        = ()
g' (Just (Just (Just x))) = ()

Here, f takes a list of lists, f' takes a list of lists of lists, g takes a Maybe that contains another Maybe(that is, Maybe (Maybe a)), and g' takes a Maybe (Maybe (Maybe a))

like image 194
Mikhail Glushenkov Avatar answered Oct 18 '22 04:10

Mikhail Glushenkov