My code is not working for example : swapElems ([],[1,2])
How can I fix it ?
swapElems :: [[a]] -> [[a]]
swapElems [] = []
swapElems [x:y:xs] = [y : x :xs]
swapElems ((x:y:s):ls) = (y:x:s): swapElems ls
swapElems [x]= [x]
CodePudding user response:
Your pattern matching does too much. You can work with three patterns:
- the empty list;
- a non-empty list where the first sublist has two or more items; and
- a non-empty list where the first list has less than two items.
You can thus define this as:
swapElems :: [[a]] -> [[a]]
swapElems [] = … -- (1)
swapElems ((x:y:xs):xss) = … -- (2)
swapElems (xs:xss) = … -- (3)
It probably however makes more sense to implement a helper function:
swap2 :: [a] -> [a]
swap2 (x:y:xs) = …
swap2 xs = xs
and then work with a mapping of swap2
:
swapElems :: [[a]] -> [[a]]
swapElems = map swap2