0
votes

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.

2

2 Answers

1
votes

If you were using Core, you could write it like this:

open Core.Std

let insert_char s c =
  String.to_list s
  |> (fun l -> List.intersperse l c)
  |> String.of_char_list

Or, equivalently:

let insert_char s c =
  let chars = String.to_list s in
  let interspersed_chars = List.intersperse chars c in
  String.of_char_list interspersed_chars

This is just straightforward use of existing librariies. If you want the implementation of List.intersperse, you can find it here. It's quite simple.

0
votes

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.