Monday, 6 June 2016

Haskell: Implement intersperse function

The intersperse function takes an element and a list and `intersperses' that element between the elements of the list.


ListUtil.hs
listIntersperse :: a -> [a] -> [a]
listIntersperse _ [] = []
listIntersperse _ [x] = [x]
listIntersperse ele (x:xs) = x : ele : listIntersperse ele xs

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> listIntersperse ',' "Hello"
"H,e,l,l,o"
*Main> 
*Main> listIntersperse '$' "Hello"
"H$e$l$l$o"
*Main> 
*Main> listIntersperse [1, 2, 3] [[1], [2], [3]]
[[1],[1,2,3],[2],[1,2,3],[3]]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment