ASD Burrito
ASD Burrito

Reputation: 172

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]

Upvotes: 6

Views: 10384

Answers (2)

Gracey W.
Gracey W.

Reputation: 11

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)

Upvotes: 1

Pierre G.
Pierre G.

Reputation: 4425

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;;

Upvotes: 5

Related Questions