Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise notation for last element of an array

Tags:

arrays

f#

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?

like image 439
Paul Jurczak Avatar asked Feb 28 '13 20:02

Paul Jurczak


3 Answers

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.

like image 63
ildjarn Avatar answered Sep 28 '22 06:09

ildjarn


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.

like image 20
Mikhail Shilkov Avatar answered Sep 28 '22 05:09

Mikhail Shilkov


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
like image 27
Marc Sigrist Avatar answered Sep 28 '22 06:09

Marc Sigrist