Home > other >  Nested functions in OCaml and their parameters
Nested functions in OCaml and their parameters

Time:04-10

I have a problem with how nested functions should be implemented in OCaml, i need the output (list) of one function to be the input of another. And both should be recursive. The problem is i've played around with the parameters and they arent feeding properly:

let toComb sentence =  
  let rec listCleanup sentence = 
    match sentence with
    | [] -> []
    | h::t when h = "" -> listCleanup t
    | h::t -> h::listCleanup t
  in
  let rec toString listCleanup sentence = 
    match listCleanup sentence  with
    | [] -> ""
    | [element] -> element
    | h::t -> h ^ " " ^ toString listCleanup sentence  
  in 
  toString listCleanup sentence;;

If I use the function and its parameter as a parameter, there's a stack overflow, but if I use just the function without a parameter, I get a mismatch of parameters. What should be the fix here?

CodePudding user response:

To correct your code, here is what would work properly:

let to_comb sentence =
  let rec cleanup s = match s with
    | [] -> []
    | ""::tail -> cleanup tail
    | hd::tail -> hd::cleanup tail in
  let rec to_string s = match s with
    | [] -> ""
    | [x] -> x
    | hd::tail -> hd ^ " " ^ to_string tail in
  to_string (cleanup s)

Note that I only call cleanup once, because you only ever need to clean the whole sequence only once. However, turns out both of these function can be expressed more simply with predefined OCaml function:

let to_comb sentence =
  sentence
  |> List.filter (fun s -> s <> "")
  |> String.concat " "

You could almost read this code out loud to get a description of what it does. It starts with a sentence, filters the empty words in it, then concatenates them with spaces in between.

  • Related