OCaml: Need help with the List.map function

advertisements

I need to create a function that basically works like this :

insert_char("string" 'x') outputs "sxtxrxixnxg".

So here is my reasoning :

Create a list with every single character in the string :

let inserer_car(s, c) =
    let l = ref [] in
for i = 0 to string.length(s) - 1 do
   l := s.[i] :: !l
done;

Then, I want to use List.map to turn it into a list like ['s', 'x', 't', 'x' etc.].

However, I don't really know how to create my function to use with map. Any help would be appreciated!

I'm a beginner in programming and especially in ocaml! so feel free to assume I'm absolutely ignorant.


A map function creates a copy of a structure with different contents. For lists, this means that List.map f list has the same length as list. So, this won't work for you. Your problem requires the full power of a fold.

(You could also solve the problem imperatively, but in my opinion the reason to study OCaml is to learn about functional programming.)

Let's say you're going to use List.fold_left. Then the call looks like this:

let result = List.fold_left myfun [] !l

Your function myfun has the type char list -> char -> char list. In essence, its first parameter is the result you've built so far and its second parameter is the next character of the input list !l. The result should be what you get when you add the new character to the list you have so far.

At the end you'll need to convert a list of characters back to a string.