Pumping Technique - Tail Recursion

In [ ]:
unwrap1 :: [[a]] -> [a]
unwrap1 []     = []
unwrap1 (xs:xss) = xs ++ unwrap1 xss
In [4]:
unwrap1 [[10,20],[30,40,50],[60]]
[10,20,30,40,50,60]
In [5]:
-- "pumping" version or "tail-recursive" version
unwrap2 :: [[a]] -> [a]
unwrap2 xss = unwrapHelper xss []

unwrapHelper :: [[a]] -> [a] -> [a]
unwrapHelper []       result = result
unwrapHelper (xs:xss) result = unwrapHelper xss (result ++ xs)
Use foldl
Found:
unwrapHelper [] result = result unwrapHelper (xs : xss) result = unwrapHelper xss (result ++ xs)
Why Not:
unwrapHelper xss result = foldl (++) result xss
In [6]:
unwrap2 [[10,20],[30,40,50],[60]]
[10,20,30,40,50,60]
In [8]:
reverse1 :: [a] -> [a]
reverse1 []     = []
reverse1 (x:xs) = reverse1 xs ++ [x]
In [9]:
reverse1 [1,2,3]
[3,2,1]
In [10]:
reverse2 :: [a] -> [a]
reverse2 xs = reverseHelper xs []

reverseHelper [] result     = result
reverseHelper (x:xs) result = reverseHelper xs (x:result)
Use foldl
Found:
reverseHelper [] result = result reverseHelper (x : xs) result = reverseHelper xs (x : result)
Why Not:
reverseHelper xs result = foldl (flip (:)) result xs
In [11]:
reverse2 [1,2,3]
[3,2,1]
In [14]:
smallest1 :: [String] -> String
smallest1 [s]     = s
smallest1 (s:ss) = min s (smallest1 ss)
In [15]:
smallest1 ["tom","john","alice"]
"alice"
In [17]:
smallest2 :: [String] -> String
smallest2 ss = smallestHelper ss (head ss)

smallestHelper :: [String] -> String -> String
smallestHelper [] result     = result
smallestHelper (s:ss) result
  | s < result = smallestHelper ss s
  | otherwise  = smallestHelper ss result
In [18]:
smallest2 ["tom","john","alice"]
"alice"
In [21]:
-- split in mergesort
split1 :: Ord a => [a] -> ([a],[a])
split1 []     = ([],[])
split1 (x:xs)
  | null xs   = ([x],[])
  | otherwise = (x:list1,head xs:list2)
                where (list1,list2) = split1 (tail xs)
In [22]:
split1 [1,2,3,4,5,6,7,8,9]
([1,3,5,7,9],[2,4,6,8])
In [ ]: