Saturday, 4 June 2016

Haskell: Concatenate two lists


ListUtil.hs
concatenate :: [a] -> [a] -> [a]
concatenate list1 list2 = if (null list1) then list2 else (head list1) : (concatenate (tail list1) list2)

Prelude> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> concatenate [] []
[]
*Main> concatenate [] [1, 2, 3]
[1,2,3]
*Main> 
*Main> concatenate [1, 2, 3] []
[1,2,3]
*Main> 
*Main> concatenate [1, 2, 3] [4, 5, 6, 7]
[1,2,3,4,5,6,7]
*Main> 
*Main> concatenate "Hari" "Krishna"
"HariKrishna"

You can also use symbols to define a function.


ListUtil.hs
(+++) :: [a] -> [a] -> [a]
list1 +++ list2 = if (null list1) then list2 else (head list1) : (tail list1 +++ list2)

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> (+++) [] []
[]
*Main> (+++) [] [1, 2, 3]
[1,2,3]
*Main> 
*Main> (+++) [1, 2, 3] []
[1,2,3]
*Main> 
*Main> (+++) [1, 2, 3] [4, 5, 6]
[1,2,3,4,5,6]


You can define like below also ‘(+++) list1 list2’.
(+++) :: [a] -> [a] -> [a]
(+++) list1 list2 = if (null list1) then list2 else (head list1) : (tail list1 +++ list2)


Following also correct ‘((+++) (tail list1) list2)’.
(+++) :: [a] -> [a] -> [a]
(+++) list1 list2 = if (null list1) then list2 else (head list1) : ((+++) (tail list1) list2)



Previous                                                 Next                                                 Home

No comments:

Post a Comment