Billy Fitt
Billy Fitt

Reputation: 99

Reverse an Array in F#

Is there any other way to reverse an Array in F# without using the array.rev function and without copying the original array, maybe similar to how you would reverse a List.

let rev (lst : List<'T>) =
  let length = List.length lst
  seq { for i in (length-1) .. -1 .. 0 do yield lst.[i] }
  |> Seq.toList

Upvotes: 1

Views: 1061

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80765

If you don't want to create a new array, the only choice is to mutate elements of the original array. Change them in place.

To reverse, just swap the first element with the last, second - with second to last, and so on:

let rev arr =
    let len = Array.length arr
    for i in 0..(len/2 - 1) do
        let x = arr.[i]
        arr.[i] <- arr.[len-i-1]
        arr.[len-i-1] <- x
    arr

Upvotes: 6

Related Questions