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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.