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:
append
function is declared by mentioning the parameters (first: integer, second: list) and the return type (list).append a [] = [a]
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
Here is the overall function code through recursion:
append :: Int -> [Int] -> [Int]append a [] = [a]append a (x:xs) = x : append a xsmain = print(append 2 [1,3,4])
append :: Int -> [Int] -> [Int]
++
operator.append a xs = xs ++ [a]
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])