March 2019
Intermediate to advanced
208 pages
5h 11m
English
Lists are designed to work hand-in-glove with recursion. Here’s a recursive function that will produce the sum of all the numbers in a list up to but not including the first negative number. (Again, you could do this with reduce, but it would require going through every item in the list.) There are two cases when recursion has to stop: when you encounter a negative number, and when you have an empty list. The latter case happens if there are no negative numbers in the list:
| | let rec sumUntilNegative = (items: list(int), total: int) : int => { |
| | switch (items) { |
| | | [] => total |
| | | [x, ..._] when x < 0 => total |
| | | [x, ...xs] => ... |
Read now
Unlock full access