How to append an element to a Haskell list

Overview

Haskell is a functional programming language in which the functions are made up of mathematical expressions. There are ways to append a number to a list in Haskell:

  1. The recursive approach
  2. The non-recursive approach

Recursive approach

  • Function declaration: In a recursive approach, the append function is declared by mentioning the parameters (first: integer, second: list) and the return type (list).
append :: Int -> [Int] -> [Int]

  • Base case: Following this, the base case is defined. This adds the number to an empty list.
append a [] = [a]

  • Recursive case: Then, the second case is defined. This separates the head of the list x and attaches it with the recursive function call to the number a (to be appended) and the tail of the list xs. As the function continues to run, it keeps splitting the head of the list and the sublists. In the end, when the list is left with no elements, it appends the number a to the list, using the base case.
append a (x:xs) = x : append a xs

Code example

Here is the overall function code through recursion:

append :: Int -> [Int] -> [Int]
append a [] = [a]
append a (x:xs) = x : append a xs
main = print(append 2 [1,3,4])

Non-recursive approach

  • Function declaration: This is a straightforward approach to append a number to a Haskell list. The declaration of the function is done in the same way as it is done for the recursive function.
append :: Int -> [Int] -> [Int]

  • Appending number: The line given below simply adds the number to the list by using the ++ operator.
append a xs = xs ++ [a]

Code example

Here is the code for the append function in Haskell when the non-recursive approach is used:

append :: Int -> [Int] -> [Int]
append a xs = xs ++ [a]
main = print(append 2 [1,3,4])

Free Resources