Slide 1

Slide 1 text

Why foldRight is beautiful Jun Tomioka (M3, inc.)

Slide 2

Slide 2 text

M3, Inc. Jun Tomioka Twitter: @jooohn1234 Github: jooohn Love: Our very first baby Had great paternity leave!

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

foldLeft / foldRight

Slide 5

Slide 5 text

trait List[+A]

Slide 6

Slide 6 text

foldLeft[B](z: B)(op: (B, A) => B): B A A A A A B A A A A B B OP ...

Slide 7

Slide 7 text

foldRight[B](z: B)(op: (A, B) => B): B A A A A A B A A A A B B OP ...

Slide 8

Slide 8 text

So what’s the difference between them?

Slide 9

Slide 9 text

Suppose you define your own Linked List

Slide 10

Slide 10 text

foldLeft would be like this

Slide 11

Slide 11 text

foldRight would be like this

Slide 12

Slide 12 text

This naive foldRight can cause stack overflow

Slide 13

Slide 13 text

If so, why can foldRight be beautiful?

Slide 14

Slide 14 text

Let’s implement “map” with foldLeft

Slide 15

Slide 15 text

A A A A A List[B] A A A A OP ... List[B] List[B]

Slide 16

Slide 16 text

Let’s implement “map” with foldLeft

Slide 17

Slide 17 text

foldRight

Slide 18

Slide 18 text

Let’s implement “map” with foldRight

Slide 19

Slide 19 text

A A A A A List[B] A A A A List[B] List[B] OP ...

Slide 20

Slide 20 text

Why is it that natural to write “map” with foldRight?

Slide 21

Slide 21 text

Immutable recursive data structure

Slide 22

Slide 22 text

Bigger part holds smaller part

Slide 23

Slide 23 text

We must create them from smaller part to bigger part

Slide 24

Slide 24 text

This is the folding order of foldRight

Slide 25

Slide 25 text

foldRight folds items by its creation order

Slide 26

Slide 26 text

Why foldRight is beautiful ● Immutable recursive data structure is built from smaller part to bigger part ● In this sense, foldRight folds items from smaller part to bigger part rather than from right to left ○ Is quite natural to treat immutable recursive data structure

Slide 27

Slide 27 text

Thanks!