How could I turn a list of integers, such as [1;2;3], into a single string "123" using fold?
Right now, I think I'm doing:
let int_list_to_string (s : int list) : string =
fold (fun s combine -> combine + .... ) ""
or something along these lines, where .... could be something similar to String.length (which I used in a different fold problem to count characters in a string) but I don't know if this is even remotely correct.
Thank you!
Your basic layout looks right to me. Many things need to be fixed up. Here are a few:
You have to pick a specific fold function to use, List.fold_left
or List.fold_right
.
The function to be folded takes two parameters. One is the accumulated result and the other is the next input from the list. The order depends on whether you use fold_left
or fold_right
. Your code sketch has two parameters but one of them is suspiciously named s
. This will not be the same s
as the input list. The names after fun
are new parameter variables introduced at that point.
The OCaml operator for concatenating strings is ^
, which is what you should use where you have +
(possibly just a placeholder in your code).
You need to convert each int to a string before concatenating. There is a function named string_of_int
that does this.
You have to apply the fold to a list. I.e., fold takes 3 arguments but you are supplying only 2 arguments in your code sketch.