Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested functions in OCaml and their parameters

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading