Home > Back-end >  Ocaml convert string list to string
Ocaml convert string list to string

Time:04-09

I'm pretty new to Ocaml and I'm doing a task where I want to convert string list to string ( string list -> string = ) where It concatenates elements by adding a space in between. Also If its a leading element it also adds "" and it ignores the empty strings.

My code so far:

let rec join list = function 
  | [] -> ""
  | [e1] -> e1
  | ""::e2 -> join list e2
  | e1::e2 -> e1 ^ list ^ join list e2 ;;

Not sure If Its correct, however I can't even test it because I don't know how to fix the error and change the parameter since It says that It's expected to call a function with a string, not string list.

Also any additional tips on how to add "" ONLY on the first leading element?

CodePudding user response:

You could just use String.concat:

String.concat " " ["foo"; "bar"; "baz"]
- : string = "foo bar baz"

CodePudding user response:

The problem is that join has type string -> string list -> string, not string list -> string, because function creates a function, it's not a match. What you want is

let rec join = function
  | [] -> ""
  | ""::tail -> join tail
  | hd::tail -> hd ^ join tail

Note that your base case [e1] -> e1 is useless, because it's also e1::[], which gets transformed into e1 ^ join [], which in turn becomes e1 ^ "", that is e1.

Also, you could do that with String.concat, but since you don't want to add space if you have an empty string, you have to filter first.

let join l =
  List.filter (fun s -> s <> "") l
  |> String.concat " "
  • Related