I am having difficulty figuring out how to split a list of Ints into a tuple containing two new lists, such that every element (starting with first) goes into the first list and every other element in the second.
Like so:
split [] = ([],[])
split [1] = ([1],[])
split [1,2] = ([1],[2])
split [1,2,3] = ([1,3],[2])
split [1,2,3,4] = ([1,3],[2,4])
I’m trying to accomplish this recursively(with guards) and only using the single argument xs
This is my approach that keeps getting error messages:
split :: [Int] -> ([Int],[Int])
split xs | length(xs) == 0 = ([],[])
| length(xs) == 1 = (xs !! 0 : [],[])
| length(xs) == 2 = (xs !! 0 : [], xs !! 1 : [])
| otherwise = (fst ++ xs !! 0, snd ++ xs !! 1) ++ split(drop 2 xs))
Your
splitfunction returns a pair, but in the last case you are using++on the result ofsplit. That will be a type error, since++works on lists, not pairs. There is also a type error becausefstandsndare functions to pick out the elements of a pair, but you are using them is a strange way.Furthermore, use pattern matching instead of using length. Also, the case where you test if the length is 2 is not needed, since the general case removes 2 elements which takes you down to the base case of the empty list.
You can also make your function more general by using a type variable
ainstead ofIntin the type.[Edit]: Added code