Saturday, 4 June 2016

Haskell: Join list of lists using a separator

Suppose if list is like ["Hi", "How", "are", "you", "ptr"], and separator is ";", your final result should be "Hi;How;are;you;ptr".


joinLists.hs
joinLists :: [[a]] -> [a] -> [a]
joinLists [] separator = []
joinLists [x] separator = x
joinLists (x:xs) separator = x ++ separator ++ joinLists xs separator

*Main> :load joinList.hs
[1 of 1] Compiling Main             ( joinList.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> joinLists ["Hi", "How", "are", "you", "ptr"] ";"
"Hi;How;are;you;ptr"
*Main> 
*Main> joinLists ["Hi", "How", "are", "you", "ptr"] "krishna"
"HikrishnaHowkrishnaarekrishnayoukrishnaptr"
*Main> 
*Main> joinLists ["Hi", "How", "are", "you", "ptr"] "$%"
"Hi$%How$%are$%you$%ptr"
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment