Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml function: replace a element in a list

I am new to OCaml and need an easy function to replace an element in a list.

After a while I got to make this work, but I don't want this count argument in the function.

let rec replaceelem ls x elem count=
  match ls with
  | [] -> ls
  | h::t -> if (count = x) then
          elem::(replaceelem t x elem (count+1))
        else
          h::(replaceelem t x elem (count+1))

Example

# let a = [1;2;3;4;5];;
val a : int list = [1; 2; 3; 4; 5]
# replaceelem a 3 99 0;;
- : int list = [1; 2; 3; 99; 5]
like image 279
ASD Burrito Avatar asked May 07 '16 17:05

ASD Burrito


People also ask

How do I remove an item from an OCaml list?

Lists in OCaml are immutable. So you can't remove things from them. You normally create another list that doesn't have the things you don't want. For this, you would use List.

What does :: do in OCaml?

It is usually used if you have a function or value that is very similar to some other, but is in some way new or modified. Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).

What does list Fold_left do in OCaml?

So fold_left is "folding in" elements of the list from the left to the right, combining each new element using the operator.

What does list ITER do OCaml?

List. iter just returns () , which is a specifically uninteresting value. I.e., List. iter is for when you just want to call a function that doesn't return anything interesting.


2 Answers

Using List.mapi - which provides the index of the element while going through the list -

let replace l pos a  = List.mapi (fun i x -> if i = pos then a else x) l;;
like image 172
Pierre G. Avatar answered Sep 29 '22 11:09

Pierre G.


If you want to get rid of that extra input (count), you can keep track of where you are in relation to your desired index (the one you're trying to replace) inside of your function by running x-1 in your recursive calls and replacing the right element when x=0. Like so:

let rec replaceelem ls x elem =
  match ls with
  | [] -> ls
  | h::t -> if (x=0) then
              elem::(replaceelem t (x-1) elem)
            else
              h::(replaceelem t (x-1) elem)
like image 22
Gracey W. Avatar answered Sep 29 '22 12:09

Gracey W.