lists
?In Haskell, lists
are a data structure that store multiple items of the same type.
[1,2,3] -- A list of integers
['a', 'b', 'c'] -- a list of characters
lists
in HaskellWe can merge two lists
through the ++
operator. The code below demonstrates the process:
merge :: [a] -> [a] -> [a]merge = \s1 -> \s2 ->case s1 of[] -> s2 -- If list1 is nil, return list2_ -> -- otherwisecase s2 of[] -> s1 -- if list2 is nil, return list1_ -> s1 ++ s2 -- otherwise merge lists using (++) operator-- call function to merge listsmain = print(merge [1,2,3] [4,5,6])
In the code above:
merge
that accepts two lists
as arguments and also returns a list
. The placeholder a
indicates that the lists
may be of any data type, but the data types of both lists
must be the same.merge
takes two lists
called s1
and s2
as parameters.case-of
statement to check if s1
is an empty list
. If s1
is empty, then merge
returns s2
in line 4.s1
is not empty, then the function checks if s2
is empty in line 7. If s2
is empty, then the function returns s1
.lists
are not empty, then the ++
operator is used to merge them in line 8.merge
function and print
the returned list
.