Content deleted Content added
→Unix pipeline: fix syntaxhighlight error |
→Functional programming: base case before the recursive case |
||
(3 intermediate revisions by one other user not shown) | |||
Line 22:
</syntaxhighlight>
For a more complex example, the [[Haskell]] code
p = partial(compose, partial(compose, f), g)
===Functional programming===
A simple example (in [[Haskell]]) is a program which computes the sum of a list of numbers. We can define the sum function recursively using a ''pointed'' style (cf. [[value-level programming|''value''-level programming]]) as:
<syntaxhighlight lang="haskell">sum [] = 0
sum (x:xs) = x + sum xs</syntaxhighlight>
However, using a [[fold (higher-order function)|fold]], this can be replaced with:
Line 133 ⟶ 130:
====jq====
[[jq (programming language)|jq]] is a [[JSON]]-oriented programming language in which the
[1,2] | add
Line 139 ⟶ 136:
evaluates to 3. (Yes, the JSON array is a jq filter that evaluates to an array.)
Although similar to Unix pipelines, jq pipelines allow the incoming data to be sent to more than one recipient on the RHS of the
[1,2] | add/length
Line 151 ⟶ 148:
evaluates to [2,3,1.5]
A dot (
1 | [., .]
Line 161 ⟶ 158:
2 | pow(.; .)
evaluates to 4 since <code>pow(x;y)</code> is x to the power y.
=====Fibonacci sequence=====
Line 169 ⟶ 166:
[0,1] | recurse( [last, add] ) | first
Here, <code>[0,1]</code> is the initial pair to be taken as the first two items
in the Fibonacci sequence. (The pair <code>[1,1]</code> could likewise be used for
the variant definition.)
The alphabetic tokens are built-in filters: `first` and `last`
emit the first and last elements of their input arrays respectively;
and
jq also allows new filters to be defined in a tacit style, e.g.:
Line 190 ⟶ 187:
In point-free style, this can be written in Python as:
example = compose(foo, bar, baz)
In jq, the equivalent point-free definition would be:
|