Skip to content

Commit 4768afc

Browse files
committed
use foldl' for insertion into tree, and explain why
1 parent bba8a33 commit 4768afc

1 file changed

Lines changed: 13 additions & 4 deletions

File tree

source_md/making-our-own-types-and-typeclasses.md

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1183,14 +1183,23 @@ We're going to start with the empty tree and then approach a list from the right
11831183

11841184
```{.haskell:hs}
11851185
ghci> let nums = [8,6,4,1,7,3,5]
1186-
ghci> let numsTree = foldr treeInsert EmptyTree nums
1187-
ghci> numsTree
1188-
Node 5 (Node 3 (Node 1 EmptyTree EmptyTree) (Node 4 EmptyTree EmptyTree)) (Node 7 (Node 6 EmptyTree EmptyTree) (Node 8 EmptyTree EmptyTree))
1186+
ghci> let numsTree = foldl' (flip treeInsert) EmptyTree nums
11891187
```
11901188

1191-
In that `foldr`, `treeInsert` was the folding function (it takes a tree and a list element and produces a new tree) and `EmptyTree` was the starting accumulator.
1189+
In that `foldl'`, `flip treeInsert` was the folding function (it takes a tree and a list element and produces a new tree) and `EmptyTree` was the starting accumulator.
11921190
`nums`, of course, was the list we were folding over.
11931191

1192+
::: {.hintbox}
1193+
We use a strict (left) fold because `treeInsert` is strict (i.e. not lazy) in its second argument.
1194+
This means that if `treeInsert x someTree` is to be evaluated, then `someTree` is guaranteed to be evaluated as well.
1195+
Postponing a guaranteed evaluation doesn't really buy us anything, but it does take up more memory and time.
1196+
:::
1197+
1198+
```{.haskell:hs}
1199+
ghci> numsTree
1200+
Node 8 (Node 6 (Node 4 (Node 1 EmptyTree (Node 3 EmptyTree EmptyTree)) (Node 5 EmptyTree EmptyTree)) (Node 7 EmptyTree EmptyTree)) EmptyTree
1201+
```
1202+
11941203
When we print our tree to the console, it's not very readable, but if we try, we can make out its structure.
11951204
We see that the root node is 5 and then it has two subtrees, one of which has the root node of 3 and the other a 7, etc.
11961205

0 commit comments

Comments
 (0)