Google
 
Web unafbapune.blogspot.com

Sunday, January 29, 2012

 

Ex 4.47 splitList

Write a function splitList that gives all the ways to split a list of at least two elements in two non-empty parts. The type declaration is:

  splitList :: [a] -> [([a],[a])]
The call splitList [1..4] should give:
  [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]
Solution 1 - using a result list:
splitList :: [a] -> [([a],[a])]
splitList xs | length xs < 2 = error "Input list must have at least 2 elements"
splitList (x:xs) = splitList' [] [x] xs where
splitList' :: [([a],[a])] -> [a] -> [a] -> [([a],[a])]
splitList' rs xs [] = rs -- rs holds the result
splitList' rs xs (y:ys) = splitList' (rs++[(xs,y:ys)]) (xs++[y]) ys
Solution 2 - without a result list:
splitList2 :: [a] -> [([a],[a])]
splitList2 [x,y] = [([x],[y])]
splitList2 (x:y:ys) = ([x],(y:ys)) : splitList2' [x,y] ys where
splitList2' :: [a] -> [a] -> [([a],[a])]
splitList2' xs [] = []
splitList2' xs (y:ys) = (xs, (y:ys)) : splitList2' (xs++[y]) ys

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?