diff options
author | Olivier Gayot <olivier.gayot@sigexec.com> | 2018-07-11 20:48:15 +0200 |
---|---|---|
committer | Olivier Gayot <olivier.gayot@sigexec.com> | 2018-07-11 20:55:23 +0200 |
commit | aa5685a9287de16d887abf7f276f6159879b3b49 (patch) | |
tree | f15d63510aac1c212cd845ced622f776111fa6b9 | |
parent | 54051fcf8a3d7ad835e9423853a93228b9ed2828 (diff) |
Make length a tail-recursive function
Signed-off-by: Olivier Gayot <olivier.gayot@sigexec.com>
-rw-r--r-- | my_list.mli | 9 |
1 files changed, 6 insertions, 3 deletions
diff --git a/my_list.mli b/my_list.mli index b21aa5d..9229064 100644 --- a/my_list.mli +++ b/my_list.mli @@ -3,9 +3,12 @@ type 'a my_list = | None (** Return the length (number of elements) of a given list. *) -let rec length = function - | Item (_, tail) -> 1 + (length (tail)) - | None -> 0 +let length my_list = + let rec aux l n = + match l with + | Item (_, tl) -> aux tl (n + 1) + | None -> n + in aux my_list 0 (** Return the first element of the given list. * Raise [Failure "hd"] if the list is empty. |