title: F# insert/remove item from list
body: <p>How should I go about removing a given element from a list? As an example, say I have list <code>['A'; 'B'; 'C'; 'D'; 'E']</code> and want to remove the element at index 2 to produce the list <code>['A'; 'B'; 'D'; 'E']</code>? I've already written the following code which accomplishes the task, but it seems rather inefficient to traverse the start of the list when I already know the index.</p>
  
  <pre><code>let remove lst i =
      let rec remove lst lst' =
          match lst with
          | []   -&gt; lst'
          | h::t -&gt; if List.length lst = i then
                        lst' @ t
                    else
                        remove t (lst' @ [h])
      remove lst []
  
  let myList = ['A'; 'B'; 'C'; 'D'; 'E']
  let newList = remove myList 2
  </code></pre>
  
  <p>Alternatively, how should I insert an element at a given position? My code is similar to the above approach and most likely inefficient as well.</p>
  
  <pre><code>let insert lst i x =
      let rec insert lst lst' =
          match lst with
          | []   -&gt; lst'
          | h::t -&gt; if List.length lst = i then
                        lst' @ [x] @ lst
                    else
                        insert t (lst' @ [h])
      insert lst []
  
  let myList = ['A'; 'B'; 'D'; 'E']
  let newList = insert myList 2 'C'
  </code></pre>