Delete the ith element of a list

Viewed 390

Write a function that deletes the ith element of a list. If the length of the list is less than i, return the list.

This is the output wanted:

- deleteIth([1,2,3,4,5,6],3);
val it = [1,2,4,5,6] : int list

- deleteIth([1,2,3,4,5,6],7);
val it = [1,2,3,4,5,6] : int list

Here's my code:

fun deleteIth (L, i) =
    let
        (* Deletes the element of a list at ith index *)
        fun delete (nil, i, position) = nil
        | delete (x::xs, i, position) = if i = position then xs else 

x :: delete (xs, i, position + 1)
        in
            if i >= 0 andalso i < length L then delete (L, i, 0) else L
        end;

note: the line x :: delete (xs, I, position + 1) should be right after the else in the previous line the line wrap made me show the code this way. Sorry for that.

But my code out puts

 - deleteIth([1,2,3,4,5,6],3);
    val it = [1,2,3,5,6] : int list

 - deleteIth([1,2,3,4,5,6],7);
    val it = [1,2,3,4,5,6] : int list

I would appreciate the help thanks.

1 Answers

Since you've got your expected results, here's a shorter version that only traverses the list once, and never beyond the element to remove.
(length must traverse the entire list to determine its length. It's possibly the least useful list function.)

The general case, k > 1 and the list is not empty:

  • To remove the k:th element, remove element k-1 from the tail of the list, then add the head of the original list to the result.

Base cases:

  • Removing element 1 from a list produces the tail of the list.
  • Removing anything from the empty list produces the empty list.

The case where the list is shorter than k will terminate when it reaches the empty list.

Like this:

fun delete_ith ([], k) = []
  | delete_ith (x::xs, 1) = xs
  | delete_ith (x::xs, k) = x :: delete_ith (xs, k - 1)
Related