Catamorphism: Difference between revisions

m
m (syntax highlighting fixup automation)
 
(16 intermediate revisions by 11 users not shown)
Line 12:
* Wikipedia article:   [[wp:Catamorphism|Catamorphism]]
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">print((1..3).reduce((x, y) -> x + y))
print((1..3).reduce(3, (x, y) -> x + y))
print([1, 1, 3].reduce((x, y) -> x + y))
Line 27 ⟶ 26:
=={{header|6502 Assembly}}==
{{works with|https://skilldrick.github.io/easy6502/ Easy6502}}
<syntaxhighlight lang="6502asm">define catbuf $10
define catbuf_temp $12
 
Line 72 ⟶ 71:
cpx #$ff
bne clear_ram</syntaxhighlight>
 
=={{header|ABAP}}==
This works in ABAP version 7.40 and above.
 
<syntaxhighlight lang=ABAP"abap">
report z_catamorphism.
 
Line 135 ⟶ 133:
concatenation(strings) = reduce in ABAP
</pre>
 
=={{header|Ada}}==
 
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO;
 
procedure Catamorphism is
Line 171 ⟶ 168:
 
<pre> 1 4 10 24</pre>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">integer s;
 
s = 0;
Line 180 ⟶ 176:
{{Out}}
<pre>45</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68"># applies fn to successive elements of the array of values #
# the result is 0 if there are no values #
PROC reduce = ( []INT values, PROC( INT, INT )INT fn )INT:
Line 208 ⟶ 203:
-13
</pre>
 
=={{header|APL}}==
<em>Reduce</em> is a built-in APL operator, written as <code>/</code>.
 
<syntaxhighlight lang="apl"> +/ 1 2 3 4 5 6 7
28
×/ 1 2 3 4 5 6 7
Line 219 ⟶ 213:
For built-in functions, the seed value is automatically chosen to make sense.
 
<syntaxhighlight lang="apl"> +/⍬
0
×/⍬
Line 230 ⟶ 224:
called, and calling <code>F/</code> with the empty list is an error.
 
<syntaxhighlight lang="apl"> {⎕←'Input:',⍺,⍵ ⋄ ⍺+⍵}/ 1 2 3 4 5
Input: 4 5
Input: 3 9
Line 240 ⟶ 234:
{⎕←'Input:',⍺,⍵ ⋄ ⍺+⍵}/ ⍬
DOMAIN ERROR</syntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
Line 248 ⟶ 241:
(Note that to obtain first-class functions from user-defined AppleScript handlers, we have to 'lift' them into script objects).
 
<syntaxhighlight lang=AppleScript"applescript">---------------------- CATAMORPHISMS ---------------------
 
-- the arguments available to the called function f(a, x, i, l) are
Line 371 ⟶ 364:
{{out}}
<pre>{55, 3628800, "12345678910"}</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; find the sum, with seed:0 (default)
print fold [1 2 3 4] => add
 
Line 384 ⟶ 376:
<pre>10
24</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|Run BASIC}}
<syntaxhighlight lang=BASIC256"basic256">arraybase 1
global n
dim n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Line 429 ⟶ 420:
end function</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{trans|Run BASIC}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 DIM n(10)
110 FOR i = 1 TO 10 : n(i) = i : NEXT i
120 SUB cat(cnt,op$)
130 temp = n(1)
140 FOR i = 2 TO cnt
150 IF op$ = "+" THEN temp = temp+n(i)
160 IF op$ = "-" THEN temp = temp-n(i)
170 IF op$ = "*" THEN temp = temp*n(i)
180 IF op$ = "/" THEN temp = temp/n(i)
190 IF op$ = "^" THEN temp = temp^n(i)
200 IF op$ = "max" THEN temp = FN MAX(temp,n(i))
210 IF op$ = "min" THEN temp = FN MIN(temp,n(i))
220 IF op$ = "avg" THEN temp = temp+n(i)
230 IF op$ = "cat" THEN temp$ = temp$+STR$(n(i))
240 NEXT i
250 IF op$ = "avg" THEN temp = temp/cnt
260 IF op$ = "cat" THEN temp = VAL(STR$(n(1))+temp$)
270 cat = temp
280 END SUB
290 '
300 PRINT " +: ";cat(10,"+")
310 PRINT " -: ";cat(10,"-")
320 PRINT " *: ";cat(10,"*")
330 PRINT " /: ";cat(10,"/")
340 PRINT " ^: ";cat(10,"^")
350 PRINT "min: ";cat(10,"min")
360 PRINT "max: ";cat(10,"max")
370 PRINT "avg: ";cat(10,"avg")
380 PRINT "cat: ";cat(10,"cat")
390 END</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{trans|Run BASIC}}
<syntaxhighlight lang="qbasic">DIM SHARED n(10)
FOR i = 1 TO 10: n(i) = i: NEXT i
 
Line 467 ⟶ 491:
PRINT "max: "; " "; cat(10, "max")
PRINT "avg: "; " "; cat(10, "avg")</syntaxhighlight>
 
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">SHARE n(10)
FOR i = 1 to 10
LET n(i) = i
Line 516 ⟶ 539:
PRINT "cat: "; " "; cat(10, "cat")
END</syntaxhighlight>
 
 
==={{header|Yabasic}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="freebasic">dim n(10)
for i = 1 to 10 : n(i) = i : next i
Line 548 ⟶ 570:
return cat
end sub</syntaxhighlight>
 
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic">
DIM a(4)
a() = 1, 2, 3, 4, 5
Line 573 ⟶ 594:
-13
120</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let reduce(f, v, len, seed) =
Line 593 ⟶ 613:
<pre>28
5040</pre>
 
=={{header|Binary Lambda Calculus}}==
 
A minimal size (right) fold in lambda calculus is <code>fold = \f\z (let go = \l.l(\h\t\z.f h (go t))z in go)</code> which corresponds to the 69-bit BLC program
 
<pre>000001000110100000010110000000010111111110111001011111101111101101110</pre>
 
=={{header|BQN}}==
Line 620 ⟶ 646:
⟨ 9 7 12 ⟩</pre>
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">( ( fold
= f xs init first rest
. !arg:(?f.?xs.?init)
Line 643 ⟶ 668:
<pre>15
120</pre>
 
=={{header|C}}==
<syntaxhighlight lang=C"c">#include <stdio.h>
 
typedef int (*intFn)(int, int);
Line 674 ⟶ 698:
-13
120</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">var nums = Enumerable.Range(1, 10);
 
int summation = nums.Aggregate((a, b) => a + b);
Line 685 ⟶ 708:
 
Console.WriteLine("{0} {1} {2}", summation, product, concatenation);</syntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
#include <functional>
Line 706 ⟶ 728:
<pre>nums_added: 15
nums_other: 30</pre>
 
=={{header|Clojure}}==
For more detail, check Rich Hickey's [http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html blog post on Reducers].
 
<syntaxhighlight lang="clojure">; Basic usage
> (reduce * '(1 2 3 4 5))
120
Line 717 ⟶ 738:
115
</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Reduction.
% First type = sequence type (must support S$elements and yield R)
% Second type = right (input) datatype
Line 757 ⟶ 777:
<pre>The sum of [1..10] is: 55
The product of [1..10] is: 3628800</pre>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">; Basic usage
> (reduce #'* '(1 2 3 4 5))
120
Line 777 ⟶ 796:
> (reduce #'expt '(2 3 4))
4096</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.meta, std.numeric,
std.conv, std.typecons;
Line 799 ⟶ 817:
gcd(T): 1
Tuple!(int,double,string)(55, 10, "12345678910")</pre>
 
=={{header|DCL}}==
<syntaxhighlight lang=DCL"dcl">$ list = "1,2,3,4,5"
$ call reduce list "+"
$ show symbol result
Line 832 ⟶ 849:
RESULT == -5 Hex = FFFFFFFB Octal = 37777777773
RESULT == 120 Hex = 00000078 Octal = 00000000170</pre>
=={{header|Delphi}}==
 
See [https://rosettacode.org/wiki/Catamorphism#Pascal Pascal].
=={{header|Déjà Vu}}==
This is a foldl:
<syntaxhighlight lang="dejavu">reduce f lst init:
if lst:
f reduce @f lst init pop-from lst
Line 847 ⟶ 865:
<pre>215
-207</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Catamorphism#Pascal Pascal].
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
;; rem : the foldX family always need an initial value
;; fold left a list
Line 872 ⟶ 887:
→ (1 1 2 6 24 120)
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<syntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
Line 896 ⟶ 910:
55 362880 12345678910
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">iex(1)> Enum.reduce(1..10, fn i,acc -> i+acc end)
55
iex(2)> Enum.reduce(1..10, fn i,acc -> i*acc end)
Line 904 ⟶ 917:
iex(3)> Enum.reduce(10..-10, "", fn i,acc -> acc <> to_string(i) end)
"109876543210-1-2-3-4-5-6-7-8-9-10"</syntaxhighlight>
 
=={{header|Erlang}}==
{{trans|Haskell}}
 
<syntaxhighlight lang="erlang">
-module(catamorphism).
 
Line 931 ⟶ 943:
{55,3628800,"12345678910"}
</pre>
 
=={{header|Excel}}==
===LAMBDA===
Line 962 ⟶ 973:
 
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">FOLDROW
=LAMBDA(op,
LAMBDA(a,
Line 1,151 ⟶ 1,162:
| ][ [[[ [ ]]] [[[ ]]] [[[ [] ]]] ]
|}
 
=={{header|F_Sharp|F#}}==
<p>In the REPL:</p>
Line 1,171 ⟶ 1,181:
val concatenation : string = "12345678910"
</pre>
 
=={{header|Factor}}==
 
<syntaxhighlight lang="factor">{ 1 2 4 6 10 } 0 [ + ] reduce .</syntaxhighlight>
{{out}}
<pre>
23
</pre>
 
=={{header|Forth}}==
Forth has three traditions for iterating over the members of a data
Line 1,210 ⟶ 1,218:
Some helper words for these examples:
 
<syntaxhighlight lang="forth">: lowercase? ( c -- f )
[char] a [ char z 1+ ] literal within ;
 
Line 1,218 ⟶ 1,226:
Using normal looping words:
 
<syntaxhighlight lang="forth">: string-at ( c-addr u +n -- c )
nip + c@ ;
: string-at! ( c-addr u +n c -- )
Line 1,240 ⟶ 1,248:
Briefly, a variation:
 
<syntaxhighlight lang="forth">: next-char ( a +n -- a' n' c -1 ) ( a 0 -- 0 )
dup if 2dup 1 /string 2swap drop c@ true
else 2drop 0 then ;
Line 1,251 ⟶ 1,259:
Using dedicated looping words:
 
<syntaxhighlight lang="forth">: each-char[ ( c-addr u -- )
postpone BOUNDS postpone ?DO
postpone I postpone C@ ; immediate
Line 1,271 ⟶ 1,279:
Using higher-order words:
 
<syntaxhighlight lang="forth">: each-char ( c-addr u xt -- )
{: xt :} bounds ?do
i c@ xt execute
Line 1,292 ⟶ 1,300:
(mostly) modifies the string in-place, and TYPE-LOWERCASE performs
side-effects and returns nothing to the higher-order word.
 
=={{header|Fortran}}==
If Fortran were to offer the ability to pass a parameter "by name", as is used in [[Jensen's_Device#Fortran|Jensen's device]], then the code might be something like <syntaxhighlight lang=Fortran"fortran"> SUBROUTINE FOLD(t,F,i,ist,lst)
INTEGER t
BYNAME F
Line 1,311 ⟶ 1,318:
However, only programmer diligence in devising functions with the correct type of result and the correct type and number of parameters will evade mishaps. Note that the EXTERNAL statement does not specify the number or type of parameters. If the function is invoked multiple times within a subroutine, the compiler may check for consistency. This may cause trouble when [[Leonardo_numbers#Fortran|some parameters are optional]] so that different invocations do not match.
 
The function's name is used as a working variable within the function (as well as it holding the function's value on exit) so that the expression <code>F(IFOLD,A(I))</code> is ''not'' a recursive invocation of function <code>IFOLD</code> because there are no (parameters) appended to the function's name. Earlier compilers did not allow such usage so that a separate working variable would be required. <syntaxhighlight lang=Fortran"fortran"> INTEGER FUNCTION IFOLD(F,A,N) !"Catamorphism"...
INTEGER F !We're working only with integers.
EXTERNAL F !This is a function, not an array.
Line 1,374 ⟶ 1,381:
Ivid 6
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type IntFunc As Function(As Integer, As Integer) As Integer
Line 1,431 ⟶ 1,437:
No op is : 0
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 1,464 ⟶ 1,469:
120
</pre>
 
=={{header|Groovy}}==
Groovy provides an "inject" method for all aggregate classes that performs a classic tail-recursive reduction, driven by a closure argument. The result of each iteration (closure invocation) is used as the accumulated valued for the next iteration. If a first argument is provided as well as a second closure argument, that first argument is used as a seed accumulator for the first iteration. Otherwise, the first element of the aggregate is used as the seed accumulator, with reduction iteration proceeding across elements 2 through n.
<syntaxhighlight lang="groovy">def vector1 = [1,2,3,4,5,6,7]
def vector2 = [7,6,5,4,3,2,1]
def map1 = [a:1, b:2, c:3, d:4]
Line 1,488 ⟶ 1,492:
84
abcd=10</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">main :: IO ()
main =
putStrLn . unlines $
Line 1,505 ⟶ 1,508:
and the generality of folds is such that if we replace all three of these (function, identity) combinations ((+), 0), ((*), 1) ((++), "") with the Monoid operation '''mappend''' (<>) and identity '''mempty''', we can still obtain the same results:
 
<syntaxhighlight lang="haskell">import Data.Monoid
 
main :: IO ()
Line 1,526 ⟶ 1,529:
 
''Prelude'' folds work only on lists, module ''Data.Foldable'' a typeclass for more general fold - interface remains the same.
 
=={{header|Icon}} and {{header|Unicon}}==
 
Works in both languages:
<syntaxhighlight lang="unicon">procedure main(A)
write(A[1],": ",curry(A[1],A[2:0]))
end
Line 1,551 ⟶ 1,553:
||: 314159
</pre>
 
=={{header|J}}==
'''Solution''':<syntaxhighlight lang="j"> /</syntaxhighlight>
'''Example''':<syntaxhighlight lang="j"> +/ 1 2 3 4 5
15
*/ 1 2 3 4 5
Line 1,563 ⟶ 1,564:
becomes
1 * 2 * 3 * 4 * 5
evaluated right to left<syntaxhighlight lang="j">
1 * 2 * 3 * 20
1 * 2 * 60
Line 1,571 ⟶ 1,572:
What are the implications for -/ ?
For %/ ?
 
=={{header|Java}}==
{{works with|Java|8}}
<syntaxhighlight lang="java">import java.util.stream.Stream;
 
public class ReduceTask {
Line 1,587:
<pre>15
120</pre>
 
=={{header|JavaScript}}==
 
===ES5===
 
<syntaxhighlight lang="javascript">var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
function add(a, b) {
Line 1,613 ⟶ 1,612:
Note that the JavaScript Array methods include a right fold ( '''.reduceRight()''' ) as well as a left fold:
 
<syntaxhighlight lang=JavaScript"javascript">(function (xs) {
'use strict';
 
Line 1,642 ⟶ 1,641:
===ES6===
 
<syntaxhighlight lang="javascript">var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
console.log(nums.reduce((a, b) => a + b, 0)); // sum of 1..10
console.log(nums.reduce((a, b) => a * b, 1)); // product of 1..10
console.log(nums.reduce((a, b) => a + b, '')); // concatenation of 1..10</syntaxhighlight>
 
=={{header|jq}}==
jq has an unusual and unusually powerful "reduce" control structure. A full description is beyond the scope of this short article, but an important point is that "reduce" is stream-oriented. Reduction of arrays is however trivially achieved using the ".[]" filter for converting an array to a stream of its values.
Line 1,662 ⟶ 1,660:
 
The "reduce" operator is typically used within a map/reduce framework, but the implicit state variable can be any JSON entity, and so "reduce" is also a general-purpose iterative control structure, the only limitation being that it does not have the equivalent of "break". For that, the "foreach" control structure in recent versions of jq can be used.
 
=={{header|Julia}}==
{{Works with|Julia 1.2}}
<syntaxhighlight lang=Julia"julia">println([reduce(op, 1:5) for op in [+, -, *]])
println([foldl(op, 1:5) for op in [+, -, *]])
println([foldr(op, 1:5) for op in [+, -, *]])</syntaxhighlight>
Line 1,674 ⟶ 1,671:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
val a = intArrayOf(1, 2, 3, 4, 5)
println("Array : ${a.joinToString(", ")}")
Line 1,693 ⟶ 1,690:
Maximum : 5
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def nums 1 2 3 4 5}
-> nums
{S.reduce {lambda {:a :b} {+ :a :b}} {nums}}
-> 15
{S.reduce {lambda {:a :b} {- :a :b}} {nums}}
-> -13
{S.reduce {lambda {:a :b} {* :a :b}} {nums}}
-> 120
{S.reduce min {nums}}
-> 1
{S.reduce max {nums}}
-> 5
</syntaxhighlight>
 
=={{header|Logtalk}}==
The Logtalk standard library provides implementations of common meta-predicates such as fold left. The example that follow uses Logtalk's native support for lambda expressions to avoid the need for auxiliary predicates.
<syntaxhighlight lang="logtalk">
:- object(folding_examples).
 
Line 1,721 ⟶ 1,734:
yes
</pre>
 
=={{header|LOLCODE}}==
 
{{trans|C}}
 
<syntaxhighlight lang=LOLCODE"lolcode">HAI 1.3
 
HOW IZ I reducin YR array AN YR size AN YR fn
Line 1,758 ⟶ 1,770:
-13
120</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang=Lua"lua">
table.unpack = table.unpack or unpack -- 5.1 compatibility
local nums = {1,2,3,4,5,6,7,8,9}
Line 1,799 ⟶ 1,810:
cat {1..9}: 123456789
</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module CheckIt {
Function Reduce (a, f) {
Line 1,835 ⟶ 1,845:
=={{header|Maple}}==
The left fold operator in Maple is foldl, and foldr is the right fold operator.
<syntaxhighlight lang=Maple"maple">> nums := seq( 1 .. 10 );
nums := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
 
Line 1,844 ⟶ 1,854:
3628800</syntaxhighlight>
Compute the horner form of a (sorted) polynomial:
<syntaxhighlight lang=Maple"maple">> foldl( (a,b) ->a*T+b, op(map2(op,1,[op( 72*T^5+37*T^4-23*T^3+87*T^2+44*T+29 )])));
((((72 T + 37) T - 23) T + 87) T + 44) T + 29</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Fold[f, x, {a, b, c, d}]</syntaxhighlight>
{{Out}}
<pre>f[f[f[f[x, a], b], c], d]</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">lreduce(f, [a, b, c, d], x0);
/* (%o1) f(f(f(f(x0, a), b), c), d) */</syntaxhighlight>
 
<syntaxhighlight lang="maxima">lreduce("+", [1, 2, 3, 4], 100);
/* (%o1) 110 */</syntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">(1 2 3 4) 0 '+ reduce puts! ; sum
(1 2 3 4) 1 '* reduce puts! ; product</syntaxhighlight>
{{out}}
Line 1,868 ⟶ 1,875:
24
</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE Catamorphism;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
 
Line 1,913 ⟶ 1,919:
<pre>Sum of [1..5]: 15
Product of [1..5]: 120</pre>
 
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace defines <tt>FoldLeft</tt>, <tt>FoldRight</tt> and <tt>Fold</tt> (an alias for <tt>FoldLeft</tt>) on any sequence that implements the <tt>IEnumerable[T]</tt> interface.
<syntaxhighlight lang=Nemerle"nemerle">def seq = [1, 4, 6, 3, 7];
def sum = seq.Fold(0, _ + _); // Fold takes an initial value and a function, here the + operator</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import sequtils
 
block:
Line 1,939 ⟶ 1,943:
words = @["nim", "is", "cool"]
concatenation = foldr(words, a & b)</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with| oo2c Version 2}}
<syntaxhighlight lang="oberon2">
MODULE Catamorphism;
IMPORT
Line 2,022 ⟶ 2,025:
-14400
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
use Collection;
 
Line 2,047 ⟶ 2,049:
120
</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml"># let nums = [1;2;3;4;5;6;7;8;9;10];;
val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
# let sum = List.fold_left (+) 0 nums;;
Line 2,055 ⟶ 2,056:
# let product = List.fold_left ( * ) 1 nums;;
val product : int = 3628800</syntaxhighlight>
 
=={{header|Oforth}}==
reduce is already defined into Collection class :
 
<syntaxhighlight lang=Oforth"oforth">[ 1, 2, 3, 4, 5 ] reduce(#max)
[ "abc", "def", "gfi" ] reduce(#+)</syntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">reduce(f, v)={
my(t=v[1]);
for(i=2,#v,t=f(t,v[i]));
Line 2,071 ⟶ 2,070:
 
{{works with|PARI/GP|2.8.1+}}
<syntaxhighlight lang="parigp">fold((a,b)->a+b, [1..10])</syntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
Should work with many pascal dialects
<syntaxhighlight lang="pascal">program reduceApp;
 
type
Line 2,134 ⟶ 2,132:
-11
-1440</pre>
 
=={{header|Perl}}==
Perl's reduce function is in a standard package.
<syntaxhighlight lang="perl">use List::Util 'reduce';
 
# note the use of the odd $a and $b globals
Line 2,145 ⟶ 2,142:
sub func { $b & 1 ? "$a $b" : "$b $a" }
print +(reduce \&func, 1 .. 10), "\n"</syntaxhighlight>
 
=={{header|Phix}}==
{{trans|C}}
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">add</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">b</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Line 2,172 ⟶ 2,168:
120
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
def add + enddef
Line 2,194 ⟶ 2,189:
getid sub reduce ?
getid mul reduce ?</syntaxhighlight>
 
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de reduce ("Fun" "Lst")
(let "A" (car "Lst")
(for "N" (cdr "Lst")
Line 2,208 ⟶ 2,201:
(bye)</syntaxhighlight>
 
=={{header|PowerShell}}==
'Filter' is a more common sequence function in PowerShell than 'reduce' or 'map', but here is one way to accomplish 'reduce':
<syntaxhighlight lang=PowerShell"powershell">
1..5 | ForEach-Object -Begin {$result = 0} -Process {$result += $_} -End {$result}
</syntaxhighlight>
Line 2,218 ⟶ 2,210:
15
</pre>
 
=={{header|Prolog}}==
 
Line 2,226 ⟶ 2,217:
* '''Ulrich Neumerkel''' wrote `library(lambda)` which can be found [http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl here]. (However, SWI-Prolog's Lambda Expressions are by default based on Paulo Moura's [https://www.swi-prolog.org/search?for=yall library(yall)])
 
<syntaxhighlight lang=Prolog"prolog">:- use_module(library(lambda)).
 
catamorphism :-
Line 2,253 ⟶ 2,244:
* The list is terminated by the special atomic thing <code>[]</code> (the empty list)
 
<syntaxhighlight lang=Prolog"prolog">
% List to be folded:
%
Line 2,264 ⟶ 2,255:
====linear <code>foldl</code>====
 
<syntaxhighlight lang=Prolog"prolog">
% Computes "Out" as:
%
Line 2,283 ⟶ 2,274:
====linear <code>foldr</code>====
 
<syntaxhighlight lang=Prolog"prolog">
% Computes "Out" as:
%
Line 2,305 ⟶ 2,296:
Functions (in predicate form) of interest for our test cases:
 
<syntaxhighlight lang=Prolog"prolog">
:- use_module(library(clpfd)). % We are using #= instead of the raw "is".
 
Line 2,336 ⟶ 2,327:
</syntaxhighlight>
 
<syntaxhighlight lang=Prolog"prolog">
:- begin_tests(foldr).
 
Line 2,390 ⟶ 2,381:
rt :- run_tests(foldr),run_tests(foldl).
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure.i reduce(List l(),op$="+")
If FirstElement(l())
x=l()
Line 2,416 ⟶ 2,406:
-13
120</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">>>> # Python 2.X
>>> from operator import add
>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']]
Line 2,438 ⟶ 2,427:
>>> </syntaxhighlight>
===Additional example===
<syntaxhighlight lang="python"># Python 3.X
 
from functools import reduce
Line 2,452 ⟶ 2,441:
 
print(summation, product, concatenation)</syntaxhighlight>
 
=={{header|Quackery}}==
Among its many other uses, <code>witheach</code> can act like reduce. In the Quackery shell (REPL):
<syntaxhighlight lang="quackery">/O> 0 ' [ 1 2 3 4 5 ] witheach +
... 1 ' [ 1 2 3 4 5 ] witheach *
...
 
Stack: 15 120</syntaxhighlight>
 
=={{header|R}}==
 
Sum the numbers in a vector:
 
<syntaxhighlight lang=R"r">
Reduce('+', c(2,30,400,5000))
5432
Line 2,472 ⟶ 2,459:
Put a 0 between each pair of numbers:
 
<syntaxhighlight lang=R"r">
Reduce(function(a,b){c(a,0,b)}, c(2,3,4,5))
2 0 3 0 4 0 5
Line 2,479 ⟶ 2,466:
Generate all prefixes of a string:
 
<syntaxhighlight lang=R"r">
Reduce(paste0, unlist(strsplit("freedom", NULL)), accum=T)
"f" "fr" "fre" "free" "freed" "freedo" "freedom"
Line 2,486 ⟶ 2,473:
Filter and map:
 
<syntaxhighlight lang=R"r">
Reduce(function(x,acc){if (0==x%%3) c(x*x,acc) else acc}, 0:22,
init=c(), right=T)
0 9 36 81 144 225 324 441
</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (fold f xs init)
Line 2,503 ⟶ 2,489:
(fold + '(1 2 3) 0) ; the result is 6
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
Any associative infix operator, either built-in or user-defined, may be turned into a reduce operator by putting it into square brackets (known as "the reduce metaoperator") and using it as a list operator. The operations will work left-to-right or right-to-left automatically depending on the natural associativity of the base operator.
<syntaxhighlight lang="raku" line>my @list = 1..10;
say [+] @list;
say [*] @list;
Line 2,523 ⟶ 2,508:
2520</pre>
In addition to the reduce metaoperator, a general higher-order function, <tt>reduce</tt>, can apply any appropriate function. Reproducing the above in this form, using the function names of those operators, we have:
<syntaxhighlight lang="raku" line>my @list = 1..10;
say reduce &infix:<+>, @list;
say reduce &infix:<*>, @list;
Line 2,530 ⟶ 2,515:
say reduce &infix:<max>, @list;
say reduce &infix:<lcm>, @list;</syntaxhighlight>
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, 1 2 3 4 5 6 7: e.List
= <Prout <Reduce Add e.List>>
<Prout <Reduce Mul e.List>>;
};
 
Reduce {
s.F t.I = t.I;
s.F t.I t.J e.X = <Reduce s.F <Mu s.F t.I t.J> e.X>;
};</syntaxhighlight>
{{out}}
<pre>28
5040</pre>
 
=={{header|REXX}}==
Line 2,537 ⟶ 2,536:
aren't a catamorphism, as they don't produce or reduce the values to a &nbsp; ''single'' &nbsp; value, but
are included here to help display the values in the list.
<syntaxhighlight lang="rexx">/*REXX program demonstrates a method for catamorphism for some simple functions. */
@list= 1 2 3 4 5 6 7 8 9 10
say 'list:' fold(@list, "list")
Line 2,590 ⟶ 2,589:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
n = list(10)
for i = 1 to 10
Line 2,626 ⟶ 2,625:
return cat
</syntaxhighlight>
=={{header|RPL}}==
≪ → array op
≪ array 1 GET 2
'''WHILE''' DUP array SIZE ≤ '''REPEAT'''
array OVER GET ROT SWAP op EVAL
SWAP 1 +
'''END''' DROP
≫ ≫ '<span style="color:blue">REDUCE</span>' STO
 
[ 1 2 3 4 5 6 7 8 9 10 ] ≪ + ≫ <span style="color:blue">REDUCE</span>
[ 1 2 3 4 5 6 7 8 9 10 ] ≪ - ≫ <span style="color:blue">REDUCE</span>
[ 1 2 3 4 5 6 7 8 9 10 ] ≪ * ≫ <span style="color:blue">REDUCE</span>
[ 1 2 3 4 5 6 7 8 9 10 ] ≪ MAX ≫ <span style="color:blue">REDUCE</span>
[ 1 2 3 4 5 6 7 8 9 10 ] ≪ SQ + ≫ <span style="color:blue">REDUCE</span>
{{out}}
<pre>
5: 55
4: -53
3: 3628800
2: 10
1: 385
</pre>
From HP-48G models, a built-in function named <code>STREAM</code> performs exactly the same as the above <code>REDUCE</code> one, but only with lists.
 
=={{header|Ruby}}==
The method inject (and it's alias reduce) can be used in several ways; the simplest is to give a methodname as argument:
<syntaxhighlight lang="ruby"># sum:
p (1..10).inject(:+)
# smallest number divisible by all numbers from 1 to 20:
p (1..20).inject(:lcm) #lcm: lowest common multiple
</syntaxhighlight>The most versatile way uses a accumulator object (memo) and a block. In this example Pascal's triangle is generated by using an array [1,1] and inserting the sum of each consecutive pair of numbers from the previous row.
<syntaxhighlight lang="ruby">p row = [1]
10.times{p row = row.each_cons(2).inject([1,1]){|ar,(a,b)| ar.insert(-2, a+b)} }
 
Line 2,648 ⟶ 2,670:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">for i = 1 to 10 :n(i) = i:next i
 
print " +: ";" ";cat(10,"+")
Line 2,685 ⟶ 2,707:
avg: 5.5
cat: 12345678910</pre>
 
=={{header|Rust}}==
 
<syntaxhighlight lang="rust">fn main() {
println!("Sum: {}", (1..10).fold(0, |acc, n| acc + n));
println!("Product: {}", (1..10).fold(1, |acc, n| acc * n));
Line 2,702 ⟶ 2,723:
Concatenation: bcdef
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object Main extends App {
val a = Seq(1, 2, 3, 4, 5)
println(s"Array : ${a.mkString(", ")}")
Line 2,713 ⟶ 2,733:
println(s"Maximum : ${a.max}")
}</syntaxhighlight>
 
=={{header|Scheme}}==
===Implementation===
reduce implemented for a single list:
<syntaxhighlight lang="scheme">(define (reduce fn init lst)
(do ((val init (fn (car rem) val)) ; accumulated value passed as second argument
(rem lst (cdr rem)))
Line 2,745 ⟶ 2,764:
21
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">say (1..10 -> reduce('+'));
say (1..10 -> reduce{|a,b| a + b});</syntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">- val nums = [1,2,3,4,5,6,7,8,9,10];
val nums = [1,2,3,4,5,6,7,8,9,10] : int list
- val sum = foldl op+ 0 nums;
Line 2,757 ⟶ 2,774:
- val product = foldl op* 1 nums;
val product = 3628800 : int</syntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
print(nums.reduce(0, +))
Line 2,769 ⟶ 2,785:
3628800
12345678910</pre>
 
=={{header|Tailspin}}==
It is probably easier to just write the whole thing as an inline transform rather than create a utility.
<syntaxhighlight lang="tailspin">
[1..5] -> \(@: $(1); $(2..last)... -> @: $@ + $; $@!\) -> '$;
' -> !OUT::write
Line 2,788 ⟶ 2,803:
 
If you really want to make a utility, it could look like this:
<syntaxhighlight lang="tailspin">
templates fold&{op:}
@: $(1);
Line 2,814 ⟶ 2,829:
120
</pre>
 
=={{header|Tcl}}==
Tcl does not come with a built-in <tt>fold</tt> command, but it is easy to construct:
<syntaxhighlight lang="tcl">proc fold {lambda zero list} {
set accumulator $zero
foreach item $list {
Line 2,825 ⟶ 2,839:
}</syntaxhighlight>
Demonstrating:
<syntaxhighlight lang="tcl">set 1to5 {1 2 3 4 5}
 
puts [fold {{a b} {expr {$a+$b}}} 0 $1to5]
Line 2,837 ⟶ 2,851:
</pre>
Note that these particular operations would more conventionally be written as:
<syntaxhighlight lang="tcl">puts [::tcl::mathop::+ {*}$1to5]
puts [::tcl::mathop::* {*}$1to5]
puts x,[join $1to5 ,]</syntaxhighlight>
But those are not general catamorphisms.
 
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
uBasic/4tH has only got one single array so passing its address makes little sense. Instead, its bounds are passed.
<syntaxhighlight lang=text"uBasic/4tH">PushFor 5,x 4,= 3,1 2,To 5 1: s@(x-1) = Used()x -: 1Next ' initialize array
' try different reductions
Print "Sum is : "; FUNC(_Reduce(_add, 5))
Print "Difference is : "; FUNC(_Reduce(_subtract, 5))
Print "Product is : "; FUNC(_Reduce(_multiply, 5))
Print "Maximum is : "; FUNC(_Reduce(_max, 5))
Print "Minimum is : "; FUNC(_Reduce(_min, 5))
 
End
' several functions
_add Param (2) : Return (a@ + b@)
_subtract Param (2) : Return (a@ - b@)
_multiply Param (2) : Return (a@ * b@)
_min Param (2) : Return (Min (a@, b@))
_max Param (2) : Return (Max (a@, b@))
 
_Reduce
Param (2) ' function and array size
Local (2) ' loop index and result
' set result and iterate array
d@ = @(0) : For c@ = 1 To b@-1 : d@ = FUNC(a@ (d@, @(c@))) : Next
Return (d@)</syntaxhighlight>
This version incorporates a "no op" as well.
<syntaxhighlight lang="text">Push 5, 4, 3, 2, 1: s = Used() - 1
For x = 0 To s: @(x) = Pop(): Next
 
Line 2,884 ⟶ 2,920:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public Sub reduce()
s = [{1,2,3,4,5}]
Debug.Print WorksheetFunction.Sum(s)
Debug.Print WorksheetFunction.Product(s)
End Sub</syntaxhighlight>
=={{header|V (Vlang)}}==
 
=={{header|Vlang}}==
{{trans|go}}
<syntaxhighlight lang=vlang>vfn"v main(vlang) {">
fn main() {
n := [1, 2, 3, 4, 5]
Line 2,922 ⟶ 2,958:
Translated from the JavaScript ES6 example with a few modifications.
 
<syntaxhighlight lang=WDTE"wdte">let a => import 'arrays';
let s => import 'stream';
let str => import 'strings';
Line 2,935 ⟶ 2,971:
# And here's a concatenation:
s.range 1 11 -> s.reduce '' (str.format '{}{}') -- io.writeln io.stdout;</syntaxhighlight>
 
=={{header|Wortel}}==
You can reduce an array with the <code>!/</code> operator.
<syntaxhighlight lang="wortel">!/ ^+ [1 2 3] ; returns 6</syntaxhighlight>
If you want to reduce with an initial value, you'll need the <code>@fold</code> operator.
<syntaxhighlight lang="wortel">@fold ^+ 1 [1 2 3] ; returns 7</syntaxhighlight>
 
{{out}}
Line 2,946 ⟶ 2,981:
3628800
12345678910</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang=ecmascript"wren">var a = [1, 2, 3, 4, 5]
var sum = a.reduce { |acc, i| acc + i }
var prod = a.reduce { |acc, i| acc * i }
Line 2,964 ⟶ 2,998:
Sum of squares is 55
</pre>
 
=={{header|Zig}}==
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1591+3fc6a2f11
 
===Reduce a slice===
<syntaxhighlight lang="zig">/// Asserts that `array`.len >= 1.
pub fn reduce(comptime T: type, comptime applyFn: fn (T, T) T, array: []const T) T {
var val: T = array[0];
for (array[1..]) |elem| {
val = applyFn(val, elem);
}
return val;
}</syntaxhighlight>
 
Usage:
 
<syntaxhighlight lang="zig">const std = @import("std");
 
fn add(a: i32, b: i32) i32 {
return a + b;
}
 
fn mul(a: i32, b: i32) i32 {
return a * b;
}
 
fn min(a: i32, b: i32) i32 {
return @min(a, b);
}
 
fn max(a: i32, b: i32) i32 {
return @max(a, b);
}
 
pub fn main() void {
const arr: [5]i32 = .{ 1, 2, 3, 4, 5 };
std.debug.print("Array: {any}\n", .{arr});
std.debug.print(" * Reduce with add: {d}\n", .{reduce(i32, add, &arr)});
std.debug.print(" * Reduce with mul: {d}\n", .{reduce(i32, mul, &arr)});
std.debug.print(" * Reduce with min: {d}\n", .{reduce(i32, min, &arr)});
std.debug.print(" * Reduce with max: {d}\n", .{reduce(i32, max, &arr)});
}</syntaxhighlight>
 
{{out}}
<pre>
Array: { 1, 2, 3, 4, 5 }
* Reduce with add: 15
* Reduce with mul: 120
* Reduce with min: 1
* Reduce with max: 5
</pre>
 
===Reduce a vector===
 
We use @reduce builtin function here to leverage special instructions if available, but only small set of reduce operators are available.
@Vector and related builtings will use SIMD instructions if possible. If target platform does not support SIMD instructions, vectors operations will be compiled like in previous example (represented as arrays and operating with one element at a time).
 
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() void {
const vec: @Vector(5, i32) = .{ 1, 2, 3, 4, 5 };
std.debug.print("Vec: {any}\n", .{vec});
std.debug.print(" * Reduce with add: {d}\n", .{@reduce(.Add, vec)});
std.debug.print(" * Reduce with mul: {d}\n", .{@reduce(.Mul, vec)});
std.debug.print(" * Reduce with min: {d}\n", .{@reduce(.Min, vec)});
std.debug.print(" * Reduce with max: {d}\n", .{@reduce(.Max, vec)});
}</syntaxhighlight>
 
{{out}}
<pre>
Vec: { 1, 2, 3, 4, 5 }
* Reduce with add: 15
* Reduce with mul: 120
* Reduce with min: 1
* Reduce with max: 5
</pre>
 
Note that std.builtin.ReduceOp.Add and std.builtin.ReduceOp.Mul operators wrap on overflow and underflow, unlike regular Zig operators, where they are considered illegal behaviour and checked in safe optimize modes. This can be demonstrated by this example (ReleaseSafe optimize mode, zig 0.11.0, Linux 6.5.11 x86_64):
 
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() void {
const vec: @Vector(2, i32) = .{ std.math.minInt(i32), std.math.minInt(i32) + 1 };
std.debug.print("Vec: {any}\n", .{vec});
std.debug.print(" * Reduce with .Add: {d}\n", .{@reduce(.Add, vec)});
std.debug.print(" * Reduce with .Mul: {d}\n", .{@reduce(.Mul, vec)});
 
var zero: usize = 0; // Small trick to make compiler not emit compile error for overflow below:
std.debug.print(" * Reduce with regular add operator: {d}\n", .{vec[zero] + vec[1]});
std.debug.print(" * Reduce with regular mul operator: {d}\n", .{vec[zero] * vec[1]});
}</syntaxhighlight>
 
{{out}}
<pre>
Vec: { -2147483648, -2147483647 }
* Reduce with .Add: 1
* Reduce with .Mul: -2147483648
thread 5908 panic: integer overflow
/home/bratishkaerik/test/catamorphism.zig:10:79: 0x20c4b0 in main (catamorphism)
std.debug.print(" * Reduce with regular add operator: {d}\n", .{vec[zero] + vec[1]});
^
/usr/lib64/zig/0.11.0/lib/std/start.zig:564:22: 0x20bee4 in posixCallMainAndExit (catamorphism)
root.main();
^
/usr/lib64/zig/0.11.0/lib/std/start.zig:243:5: 0x20bdc1 in _start (catamorphism)
asm volatile (switch (native_arch) {
^
???:?:?: 0x0 in ??? (???)
[1] 5908 IOT instruction ./catamorphism
</pre>
 
For well-defined overflow/underflow behaviour you can use wrapping and saturating operators (for addition they are +% and +| respectively). With +% and *% (wrapping multiplication) operators, behaviour should be identical to .Add and .Mul reduce operators.
 
=={{header|zkl}}==
Most sequence objects in zkl have a reduce method.
<syntaxhighlight lang="zkl">T("foo","bar").reduce(fcn(p,n){p+n}) //--> "foobar"
"123four5".reduce(fcn(p,c){p+(c.matches("[0-9]") and c or 0)}, 0) //-->11
File("foo.zkl").reduce('+(1).fpM("0-"),0) //->5 (lines in file)</syntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<syntaxhighlight lang="zxbasic">10 DIM a(5)
20 FOR i=1 TO 5
30 READ a(i)
56

edits