hi e erybody
i have a list [“first” ; “second” ; “three”]
i want to return this list without the last element like that :retourne [“first” ; “second” ]*)
I try this but something doesn’t function:
let rec remove_last l =
let lgth = List_length l in
let ret = [] in
if lgth < 2 then ret
else List.hd l :: remove_last (List.tl l);;
print_string (remove_last l ["first" ; "second" ; "last"]);;
Please tell us what doesn’t work and the error messages you see, it makes it easier for us to help you.
In this case I suspect you need to replace List_length by List.length and your code should be right.
However note that calling List.length l on each recursive call needs to go through the whole l which is inefficient (see the implementation of List.length).
This is a case where you should use pattern matching. Here’s the structure, I’ll let you fill in the blanks:
let rec remove_last l = match l with
| [] -> …
| [v] -> …
| v :: vs -> …
The way to work with lists is to use pattern matching:
let rec remove_last = function
| [] | [_] -> []
| x :: xs -> x :: remove_last xs
If you don’t understand anything about the language, then it may be a good idea to start by reading about the basics, I recommend OCaml from the Very Beginning.
The ocaml type system is like this toy for children, you can not put a triangle in the square shape.
Here remove_last returns a string list, but print_string expects a string.
So here you can use List.iter to apply print_string on every elements of the list, or you can also use String.concat to concatenate every string of the list into a single string:
$ ocaml
# let rec remove_last = function
| [] | [_] -> []
| x :: xs -> x :: remove_last xs
;;
val remove_last : 'a list -> 'a list = <fun>
# print_string (remove_last ["first" ; "second" ; "last"]) ;;
Error: This expression has type string list
but an expression was expected of type string
# List.iter print_string (remove_last ["first" ; "second" ; "last"]) ;;
firstsecond
- : unit = ()
# print_string (
String.concat " " (remove_last ["first"; "second"; "last"])) ;;
first second
- : unit = ()
(copy-pasted from the toplevel)
$ ocaml
# List.iter ;;
- : ('a -> unit) -> 'a list -> unit = <fun>
# String.concat ;;
- : string -> string list -> string = <fun>