Uses of Γ
The main use of the built-in Γ
, known as pattern matching on lists or list deconstruction, is to split a list into a head and tail, and apply a binary function on them.
This corresponds to the Haskell pattern matching idiom
f (x : xs) = <something>
f [] = <something else>
where <something>
is an expression containing x
, xs
and possibly f
.
There are 4 overloadings of Γ
, each of which works a little differently.
list
The first overloading, list
, takes a value a
and a binary function f
.
It returns a new function that takes a list, returns a
if it's empty, and calls f
on the head and tail if it's nonempty.
For example, Γ_1€
takes a list, returns -1
if it's empty, and the index of first occurrence of the first element in the tail if not.
listN
The second overloading, listN
, is similar to list
, except that a
is omitted and the default value of the return type is used instead.
For example, Γ€
is equivalent to Γ0€
, since the default numeric value is 0
.
In practice, listN
is used more often than list
, since the default value is either irrelevant or exactly what you need.
A common pattern is Γ~αβγ
, where αβγ
are three functions; this applies β
to the first element and γ
to the tail, and combines the results with α
.
It was used e.g. in this answer.
Other patterns include Γo:α
for applying α
only to the first element, and Γ·:mα
for applying α
to all elements except the first.
The latter was used in this answer.
listF
The third overloading is a bit more involved.
Like list
, it takes a value a
and a function f
, and returns a new function g
that takes a list.
However, this time f
takes an extra function argument, which is g
itself, and can call it on any value (including, but not limited to, the tail of the input list).
This means that listF
implements a general recursion scheme on lists.
listF
is not used very often, since explicit recursion with list
/listN
is usually of the same length or shorter, as in this answer.
listNF
listNF
is to listF
what listN
is to list
: the input a
is omitted, and the default value of the return type is used instead.
In rare circumstances, it can be shorter than a right fold, for example in this answer.
As an example of the recursive versions of Γ
, the function Γλ·:o⁰↔
shuffles a list in the order first, last, second, second-to-last, third, third-to-last, and so on.
Try it online!
The function f
is the explicit lambda λ·:o⁰↔
, whose argument ⁰
is the entire function.
What f
does is reverse the tail with ↔
, then call the main function recursively with o⁰
, and finally tack the head back with ·:
.
Of course, Γ·:o₀↔
is a byte shorter, but doesn't work if the line contains something else than this function.
5I wouldn't say it is new... – totallyhuman – 2018-01-06T16:09:46.907
1
@totallyhuman first Husk answer Still not that new
– H.PWiz – 2018-01-06T16:17:30.143