Higher-order functions: Difference between revisions

Content added Content deleted
m (→‎{{header|Quackery}}: clarification)
(→‎{{header|Quackery}}: replaced my previous solution with one that defines map and filter in terms of fold)
Line 3,523: Line 3,523:
=={{header|Quackery}}==
=={{header|Quackery}}==


First define the higher order functions <code>map</code>, <code>filter</code>, and <code>fold</code>.
First define the higher order functions <code>fold</code>, <code>map</code>, and <code>filter</code>.


<pre> [ stack ] is map.act ( --> s )
<pre> [ stack ] is fold.act ( --> s )
protect map.act

[ map.act put
[] swap witheach
[ map.act share do
nested join ]
map.act release ] is map ( [ x --> [ )

[ stack ] is filter.act ( --> s )
protect filter.act

[ filter.act put
[] swap witheach
[ dup
filter.act share do
iff [ nested join ]
else drop ]
filter.act release ] is filter ( [ x --> [ )

[ stack ] is fold.act ( --> s )
protect fold.act
protect fold.act


Line 3,553: Line 3,533:
witheach
witheach
[ fold.act share do ] ]
[ fold.act share do ] ]
fold.act release ] is fold ( [ x --> x )</pre>
fold.act release ] is fold ( [ x --> x )


[ ' [ [ ] ] rot join swap
Then test them in the Quackery shell by reversing every string in a nest of strings, removing all the negative numbers from a nest of numbers, and flattening a deeply nested nest.
nested
' [ nested join ] join
fold ] is map ( [ x --> [ )


[ ' [ [ ] ] rot join swap
<pre>/O> $ "esreveR yreve gnirts ni a tsen fo .sgnirts" nest$
nested ' dup swap join
' [ iff [ nested join ]
else drop ] join
fold ] is filter ( [ x --> [ )
</pre>

Then test them in the Quackery shell by flattening a deeply nested nest, reversing every string in a nest of strings, and removing all the negative numbers from a nest of numbers.

<pre>/O> ' [ 1 2 [ [ 3 4 ] ] 5 [ 6 [ 7 [ 8 [ 9 ] ] ] ] ]
... [ dup
... ' join fold
... tuck = until ]
... echo
...
[ 1 2 3 4 5 6 7 8 9 ]
Stack empty.

/O> $ "esreveR yreve gnirts ni a tsen fo .sgnirts" nest$
... ' reverse map
... ' reverse map
... witheach [ echo$ sp ]
... witheach [ echo$ sp ]
Line 3,569: Line 3,570:
...
...
[ 42 23 ]
[ 42 23 ]
Stack empty.
Stack empty.</pre>

/O> ' [ 1 2 [ [ 3 4 ] ] 5 [ 6 [ 7 [ 8 [ 9 ] ] ] ] ]
... [ dup
... ' join fold
... tuck = until ]
... echo
...
[ 1 2 3 4 5 6 7 8 9 ]
Stack empty.
</pre>


=={{header|R}}==
=={{header|R}}==