Reputation: 99
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
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