Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Fold vs Reduce

fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters. reduce doesn’t take an initial value, but instead starts with the first element of the collection as the accumulator (called sum in the following example).

0.until(3).foreach { println }
0
1
2
(0 until 3).foreach{println}
0
1
2
0.until(9).by(2).foreach { println }
0
2
4
6
8
(0 until 9 by 2).foreach { println }
0
2
4
6
8
(9 until 0 by -2).foreach { println }
9
7
5
3
1

to

to is inclusive on both ends.

0.to(3).foreach{
    println
}
0
1
2
3
(0 to 3).foreach{
    println
}
0
1
2
3
0.to(9).by(2).foreach { println }
0
2
4
6
8
(0 to 9 by 2).foreach { println }
0
2
4
6
8
3.to(0).by(-1).foreach{ println }
3
2
1
0