Search code examples
f#functional-programmingsequences

Swapping every pair of items in an F# list


I'm positive that there is a better way to swap items in a list by pairs ( [1;2;3;4] -> [2;1;4;3] ) as I'm doing too many appends for my liking but I'm not sure how best to do it.

let swapItems lst =
    let f acc item =
        match acc with
        | [] -> [item]
        | hd :: next :: tl when tl <> [] -> [next] @ tl @ [item;hd]
        | _ -> item :: acc
    List.fold f [] lst

How can I improve this? This only works on lists that have an even length.


Solution

  • What about this:

    let rec swapItems = function
        | []
        | _::[] as l -> l
        | a::b::t ->
            b::a::(swapItems t)
    

    ?