Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

haskell
communitycreator

How to append an element to a Haskell list

Mahnoor Zaheer

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]
Declaration of the "append" function in Haskell

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

  • 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
Recursive case for the "append" function in Haskell

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])
The code for the "append" function in Haskell (recursion)

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]
Declaration of the "append" function in Haskell

  • Appending number: The line given below simply adds the number to the list by using the ++ operator.
append a xs = xs ++ [a]
Appending a number to a list in Haskell (non-recursive)

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])
The code for the "append" function in Haskell (non-recursion)

RELATED TAGS

haskell
communitycreator
RELATED COURSES

View all Courses

Keep Exploring