Fold: Difference between revisions

From The K Language Wiki
Content added Content deleted
(add fold page)
 
("More lowercasing")
 
(4 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{{primitive|f/y<br>x f/y}}
{{primitive|f/y<br>x f/y}}


'''Fold''', also known as '''reduce''', '''foldl''' and '''over''', takes a dyadic function <code>f</code> and reduces an array <code>y</code> using it.
'''fold''', also known as '''reduce''', '''foldl''' and '''over''', takes a [[dyadic]] function <code>f</code> and reduces an array <code>y</code> using it.


Fold is a very strong utility. For example, you can sum a list using <code>+/</code>.
Fold is a very strong utility. For example, you can sum a list using <code>+/</code>.
Line 23: Line 23:
13
13
</pre>
</pre>

When used with functions that take more than 2 arguments, fold can take multiple arguments, of which the first one is always the initial value.

<pre>
{x,y,z}/["A";1 2 3;"BCD"]
("A";1;"B";2;"C";3;"D")
</pre>

[[Category:Adverbs]]
[[Category:Primitives]]

Latest revision as of 04:42, 9 July 2022

Fold
f/y
x f/y

fold, also known as reduce, foldl and over, takes a dyadic function f and reduces an array y using it.

Fold is a very strong utility. For example, you can sum a list using +/.

 +/1 2 3 4
10
 ,/("ab";1;`d`a`b)
("a"
 "b"
 1
 `d
 `a
 `b)

Specifying a left argument x uses it as an initial value.

 3 +/1 2 3 4
13

When used with functions that take more than 2 arguments, fold can take multiple arguments, of which the first one is always the initial value.

{x,y,z}/["A";1 2 3;"BCD"]
("A";1;"B";2;"C";3;"D")