From aa5685a9287de16d887abf7f276f6159879b3b49 Mon Sep 17 00:00:00 2001 From: Olivier Gayot Date: Wed, 11 Jul 2018 20:48:15 +0200 Subject: Make length a tail-recursive function Signed-off-by: Olivier Gayot --- my_list.mli | 9 ++++++--- 1 file 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. -- cgit v1.2.3