Reputation: 91
I have this function:
swap [] = []
swap [a] = [a]
swap a = last a : (init . tail $ a) ++ [head a]
If I use this on a list with lists, it just turns each list around, and not the elements in each list. What am I missing here?
Upvotes: 0
Views: 177
Reputation: 91857
swap
takes a list of things, and exchanges its first element for its last. Since there is nothing in there about looking inside of those elements at all, it definitely will not modify any of the elements inside of a list.
But if you have a list of things, and you want to perform some modification of each item in the list, there is a function for that already: map
. And the modification you want to perform is swap
, so let's see how the types line up.
map :: ( a -> b) -> [a] -> [b]
swap :: [a] -> [a]
map swap :: [[a]] -> [[a]]
So map swap
takes a list of lists, and swaps each of those sublists, without changing the order of the "larger" list at all.
Upvotes: 1