Sunday 5 June 2016

Haskell: Implement unzip function

Define the unzip function, which takes a list of tuples and returns two lists, one with all the first components and other one with the seconds. For example, unzip [(1,2),(3,4)] =([1,3],[2,4]).


ListUtil.hs
{-# LANGUAGE BangPatterns #-}
unzipCon :: [(a, a)] -> ([a], [a])
unzipCon [] = ([], [])
unzipCon xs = unzipData [] [] xs

unzipData :: [a] -> [a] -> [(a,a)] -> ([a], [a]) 
unzipData !xs !ys [] = (xs, ys)
unzipData !xs !ys (d:ds) = unzipData (xs ++ [fst (d)] ) (ys ++ [snd (d)] ) ds

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment