Question

I'm trying to the learn the basics of F# right now and was wondering how you could replace a element in a list recursively. So you would do something like this.

Was it helpful?

Solution 2

A modification of the answer I linked to directly answer the question:

let rec insert v i l = //v - value to substitute, i - index at which to substitute, l - the list
    match i, l with
    | 0, x::xs -> v::xs //this line does the actual replace
    | i, x::xs -> x::insert v (i - 1) xs //simply iterates one further through the list
    | i, [] -> failwith "index out of range" // the given index is outside the bounds of the list

Note that this is not tail recursive and will Stackoverflow for large lists. Arrays or List would probably be a better choice if you need to do this type of operation.

OTHER TIPS

let replace index sub = List.mapi (fun i x -> if i = index then sub else x)

replace 0 'd' ['a';'b';'c'] 
> val it : char list = ['d'; 'b'; 'c']

This meets your criteria, with two minor changes to make it more conformant with F# style:

  1. the index is zero-based
  2. the list is the last argument, to support piping
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top