Brief notation of the last element of the array

Is there a short notation for accessing the last element of an array similar to std :: vector :: back () in C ++? Should I write:

veryLongArrayName.[veryLongArrayName.Length-1] 

everytime?

+4
source share
3 answers

Comment extension

The built-in Seq.last veryLongArrayName option Seq.last veryLongArrayName , but note that this is O (N), not O (1), so for all but the smallest arrays, it is probably too inefficient for practical use.

However, there is no harm in abstracting this functionality:

 [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] [<RequireQualifiedAccess>] module Array = let inline last (arr:_[]) = arr.[arr.Length - 1] 

Now you can make Array.last veryLongArrayName without any overhead, while keeping the code very idiomatic and readable.

+10
source

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 
+6
source

I cannot find it in official docs, 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 the implementation on github .

+5
source

All Articles