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]
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.
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] ).
So fold_left is "folding in" elements of the list from the left to the right, combining each new element using the operator.
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.
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;;
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With