How to remove the nth element from a list in Haskell

Overview

Haskell is a functional programming language. A functional programming language is a programming paradigm focusing on changing data through expressions that don’t have side effects. These expressions are often called pure functions. We will write a pure function that removes the nth element from a list in this shot. Let’s break down the problem before jumping to the code.

Recursive solution

Functional programming encourages us to define the problem in a more abstract way, independent of the concrete order of instructions. Often, it is helpful to break down the problem into smaller valid problems and solve them recursively.

Let’s take an example of a list [1,2,3,4], from which we want to remove the element at position 1. The answer should be [1,3,4].

  • The most simple removal is at position 0. If n is 0, then our problem is simple. The answer is the list with its head removed.

  • To solve the n problem, let’s assume that our function correctly solves the n-1 problem and we have access to its solution. In our case, the n-1 problem is removing the 0th element in [2,3,4]. The correct solution for this problem is [3,4].

  • Now note that if we add the head of the original list (1) to the above solution ([3,4]), we solve the n problem! That is [1,3,4].

Program

Below is the Haskell program for splitting a list at position n:

removeNth :: Int -> [] a -> [] a
removeNth = \n -> \list ->
case n of
0 -> tail list
otherwise -> head list: removeNth (n-1) (tail list)
main = print (removeNth 1 [1,2,3,4])

Explanation

  • In line 1, removeNth :: Int -> [] a -> [] a) is a type annotation for our function called removeNth. Haskell is statically typed, and every function or variable has a type. In this case, removeNth is a function that takes an integer (the position n) and a list of any type as its argument and returns a list with the nth element removed.

  • In line 2, we have the function definition, which shows that our function takes an integer n, and a list and a case expressions that implement our recursive formulation of the problem.

  • In line 4, the first equation represents the base case as discussed above. Note that head and tail are built-in Haskell functions that return the head of the list and the remainder of the list, respectively.

  • In line 5, the second equation represents our recursive definition. Using head list: removeNth (n-1) (tail list), we remove the element at position n-1 of the list with its head removed and attach the head of the original list at the start, giving us the desired solution.

In the above explanation, we avoided visualizing what happened in the program during the execution of a recursive function. Instead, we focused on its essence, i.e., treating the recursive function as a black box that can solve smaller valid problems.

Free Resources