3Pattern matching deconstructs a value to bring zero or more expressions into scope. Pattern matches are introduced with the `case` keyword.
5Pattern matches have the following general form
14Pattern matching can also be used in the declaration of functions, as we have already seen:
17fn pattern_1 ... pattern_n = result
20Any of the above types of pattern are also valid when introducing functions. In addition, patterns can also be grouped in parentheses to introduce multiple-arugument functions. For example,
23example x (y, z) w = x * y + z * w
26The following pattern types are supported:
37Patterns need not be exhaustive. A pattern match failed exception will be thrown at runtime if no pattern matches the input.
41The wilcard `_` matches any input and brings nothing into scope:
50Literal patterns are provided to match on primitives:
68A variable pattern matches any input and binds that input to its name:
77Array patterns match an input which is an array, and bring its elements into scope.
82f = \arr -> case arr of
84 [x, y] -> x * y + f xs
88Here, the first pattern only matches arrays of length one, and brings the first element of the array into scope.
90The second pattern matches arrays with two elements, and brings the first and second elements into scope.
94The head and tail of a non-empty array can be matched by using a cons pattern:
97add = \arr -> case arr of
102`:` associates to the right:
105addPairs = \arr -> case arr of
106 x : y : xs -> x * y + addPairs xs
112Record patterns match an input which is a record, and bring its properties into scope.
116 { foo = "Foo" } -> o.bar
122The patterns above can be combined to create larger patterns.
128 { arr = x : _, take = "car" } -> x
129 { arr = _ : x : _, take = "cadr" } -> x
135Named patterns bring additional names into scope when using nested patterns. Any pattern can be named by using the `@` symbol:
138f = \arr -> case arr of
139 a@(_ : _ : _) -> true
143Here, in the first pattern, any array with two or more elements will be matched and bound to the variable `a`.
147Guards are used to impose additional constraints inside a pattern using boolean-valued expressions, and are introduced with a pipe after the pattern:
150evens = \arr -> case arr of
152 x : xs | x % 2 == 0 -> 1 + evens xs
156When defining a function, guards appear after all patterns:
159greater x y | x > y = true
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list