Haskel Puzzle Solved

May 18, 2008

Disclaimer

Don’t expect this post to be breaking any barriers. I’ve been struggling with to solve an exercise from my Haskell Road book for the past week or so and I finally cracked it.

I’d be interested to know if anyone has a better way to solve it. I’m still very much a Haskell beginner and haven’t gotten much past pattern matching, guards and the where clause; so try not to confuse me.

The Problem

Create a function

splitList :: [a] -> [([a],[a])]

Which takes a list

[1..5]

and returns a list;

[([1], [2,3,4,5]), ([1,2], [3,4,5]), ([1,2,3], [4,5]), ([1,2,3,4], [5])]

My Solution

moveHeadToTail :: [a] -> [a] -> [a]
moveHeadToTail (xs) (y:ys) = xs ++ [y]

splitListAux :: [a] -> [a] -> [([a],[a])]
splitListAux (o:os) [] = [([o],os)] ++ splitListAux os [o]
splitListAux (o:os) h
      | length (o:os) == 2 = [(head,os)]
      | otherwise = [(head,os)] ++ splitListAux os head
          where
          head = moveHeadToTail h (o:os)

splitList :: [a] -> [([a],[a])]
splitList (x:xs) = splitListAux (x:xs) []