Skip to content

Commit aa998d3

Browse files
authored
fix(Collections § Lists sumEachItem): Tail recursion (#42)
1 parent 0b59ee2 commit aa998d3

1 file changed

Lines changed: 5 additions & 3 deletions

File tree

docs/fsharp-cheatsheet.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -375,10 +375,12 @@ match myList with
375375
| head :: tail -> ... // cons pattern; matches non-empty. `head` is the first item, `tail` is the rest
376376
377377
// Tail-recursion with a list, using cons pattern
378-
let sumEachItem (myList:int list) =
378+
[<TailCall>]
379+
let rec sumEachItem' (acc:int) (myList:int list) =
379380
match myList with
380-
| [] -> 0
381-
| head :: tail -> head + sumEachItem tail
381+
| [] -> acc
382+
| head :: tail -> sumEachItem' (acc + head) tail
383+
let sumEachItem (myList:int list) = sumEachItem' 0 myList
382384
```
383385

384386
See the [List Module](https://fsharp.github.io/fsharp-core-docs/reference/fsharp-collections-listmodule.html) for built-in functions.

0 commit comments

Comments
 (0)