Re: "ocaml_beginners"::[] reverse a list. is this a good solution
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
Le 2014-10-20 12:56, Roelof Wobben [email protected] [ocaml_beginners] a écrit : > Hello, > > I try the 99 ocaml problems and have solved the reverse a list > problem. > > My solution looks like this : > > let rec test l1 l2 = > match l1 with > | [] -> l2 > | h :: t -> test t (h::l2) > ;; > > Is this a good way to solve it or are there things that can be better > ? > This is a good way :) You've written a tail recursive function[1] ! [1] https://en.wikipedia.org/wiki/Tail_call But this is not yet finished : your function takes 2 arguments, and you expect the second to be an empty list. What will happen if someone call your function like this ? > test [ "a" ; "b" ; "c"] [ "1" ; "2" ; "3"];; Is there a way to « hide » your algorithm, and get a function which takes only one list ? (Hint : you can wrap a function inside another one…) -- Sébastien