I’d like to know how to swap every second element of a list in Haskell.
Example output should look like this:
swap [1,2,3,4,5]
[2,1,4,3,5]
What I have so far is
swap :: [a] -> [a]
swap [] = []
swap (x:xs) = head xs : [x]
but this only swaps the first two elements and any attempt I make to make the function recursive causes errors when I try to load the file that contains the function. How to make it recursive?
You need to grab out 2 elements at a time:
The last line is needed to allow odd-length lists — it matches a list having length exactly 1, so it doesn’t overlap either of the other 2 cases (length 0, and length 2 or more).