How to check in the next "head" in OCaml is empty?

I am new to OCaml (and still new to learning programming in general), and I have a quick question about checking which line contains the next item in a list of strings.

I want it to put a separator between each element of the line (except the last), but I cannot figure out how to make the program "know" that the last element is the last element.

Here is my code as of now:

let rec join (separator: string) (l : string list) : string = begin match l with | []->"" | head::head2::list-> if head2=[] then head^(join separator list) else head^separator^(join separator list) end let test () : bool = (join "," ["a";"b";"c"]) = "a,b,c" ;; run_test "test_join1" test 

Thanks in advance!

+8
list functional-programming ocaml
source share
2 answers

You are almost there. An idea splits a list in three cases when it has 0, 1, or at least 2 elements. If the list contains more than one item, you can insert separator in the output line:

 let rec join (separator: string) (l : string list) : string = begin match l with | [] -> "" | head::[] -> head | head::list-> head^separator^(join separator list) end 

I have a few comments about your function:

  • Type annotations are redundant. Since (^) is a string concatenation operator, a type checker can print separator , l types and output functions easily.
  • No need to use a begin/and pair. Since you have only one level of pattern matching, the compiler does not confuse.
  • You can use function to exclude the match l with .

Therefore, your code may be abbreviated as:

 let rec join sep l = match l with | [] -> "" | x::[] -> x | x::xs -> x ^ sep ^ join sep xs 

or even more concise:

  let rec join sep = function | [] -> "" | x::[] -> x | x::xs -> x ^ sep ^ join sep xs 
+9
source share

An empty list is [] , a list with one element is [h] , and a list with at least one element is h::t . Thus, your function can be written as:

 let rec join separator = function | [] -> "" | [h] -> h | h::t -> h ^ separator ^ join separator t 
+7
source share

All Articles