I'm new to Haskell and have been given a worksheet question which has me stumped. The question is asking me to define a function that takes a list and returns a list of tuples, each of which contains a sub list of the original list.
I have tried the below. However, as expected, on each recursion the the previous head gets dropped.
splits :: [Int] -> [([Int],[Int])]
splits []
= [([],[])]
splits (l:ls)
= ([] [l], ls) : splits ls
Here is the result I get.
[([1],[2,3,4]),([2],[3,4]),([3],[4]),([4],[]),([],[])]
Any advice on how to do this would be appreciated!
CodePudding user response:
You only need to prepend the first items in the result of the recursive call with l
, so
splits :: [a] -> [([a], [a])]
splits [] = []
splits (l:ls) = ([l], ls) : map f (splits ls)
where f (x, y) = (l:x, y)
or with first
:
import Control.Arrow(first)
splits :: [a] -> [([a], [a])]
splits [] = []
splits (l:ls) = ([l], ls) : map (first (l:)) (splits ls)
CodePudding user response:
This also removes the item which has an empty tail :
splits :: [Int] -> [([Int], [Int])]
splits [] = []
splits [x] = []
splits (x : xs) = ([x], xs) : map f (splits xs)
where
f (z, y) = (x : z, y)