Skip to content

Commit 3783bc3

Browse files
Add detailed explanation of :: operator in range function (#1861)
Elaborated on the role of the `::` operator within the `range` function. This operator is essential for understanding how the list is built recursively. It's used to prepend the current `lo` value to the front of the list returned by the recursive call to `range`. --------- Co-authored-by: Cuihtlauac Alvarado <[email protected]>
1 parent 630b5b9 commit 3783bc3

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

data/tutorials/getting-started/1_01_a_tour_of_ocaml.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ val range : int -> int -> int list = <fun>
246246
- : int list = [2; 3; 4; 5]
247247
```
248248

249-
As indicated by its type `int -> int -> int list`, the function `range` takes two integers as parameters and returns a list of integers as result. The first `int` parameter, called `lo`, is the lower bound of the range; the second `int` parameter, called `hi`, is the higher bound of the range. It is assumed that `lo <= hi`. If this isn't the case, the empty range is returned. That's the first branch of the `if … then … else` expression. Otherwise, the `lo` value is appended at the front of a list that is going to be created by calling `range` itself. That is recursion. The function `range` calls itself. However, some progress is made at each call. Here, since `lo` has just been appended at the head of the list, `range` is called with the `lo + 1`. This can be visualised this way:
249+
As indicated by its type `int -> int -> int list`, the function `range` takes two integers as parameters and returns a list of integers as result. The first `int` parameter, `lo`, is the range's lower bound; the second `int` parameter, `hi`, is the higher bound. If `lo <= hi`, the empty range is returned. That's the first branch of the `if … then … else` expression. Otherwise, the `lo` value is prepended to the list created by calling `range` itself; this is recursion. Preprending is achieved using `::`, the cons operator in OCaml. It constructs a new list by adding an element at the front of an existing list. Progress is made at each call; since `lo` has just been appended at the head of the list, `range` is called with `lo + 1`. This can be visualised this way:
250250
```
251251
range 2 5
252252
= 2 :: range 3 5

0 commit comments

Comments
 (0)