Is there a concise notation to access last element of an array, similar to std::vector::back() in C++? Do I have to write:
veryLongArrayName.[veryLongArrayName.Length-1]
each time?
Expanding from comment
The built-in option is Seq.last veryLongArrayName
, but note that this is O(N) rather than O(1), so for all but the smallest arrays probably too inefficient for practical use.
That said, there's no harm in abstracting this functionality yourself:
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
[<RequireQualifiedAccess>]
module Array =
let inline last (arr:_[]) = arr.[arr.Length - 1]
Now you can do Array.last veryLongArrayName
with no overhead whatsoever, while keeping the code very idiomatic and readable.
I can not find it in the official documents, but F# 4 seems to have Array.last
implemented out of the box:
/// Returns the last element of the array.
/// array: The input array.
val inline last : array:'T [] -> 'T
Link to implementation at github.
As an alternative to writing a function for _[], you can also write an extension property for IList<'T>:
open System.Collections.Generic
[<AutoOpen>]
module IListExtensions =
type IList<'T> with
member self.Last = self.[self.Count - 1]
let lastValue = [|1; 5; 13|].Last // 13
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With