Skip to content

Change definition of last for 2.0 #58313

Open
@CameronBieganek

Description

@CameronBieganek

This issue is similar to #42943, but this issue focuses on changes to the definition (i.e. docstring) for last for version 2.0 (if that ever happens). In #42943, it was proposed to change the default implementation of last to last(x) = first(Iterators.reverse(x)). A PR with that change was merged and then reverted because it was too breaking. Unfortunately, the last docstring guarantees that last uses lastindex.

We already have syntax sugar for getting the last element of an indexable object that has a lastindex method, i.e. x[end]. So, it is redundant for last to use the same definition. It makes more sense for last to be defined in terms of iteration. I propose the following definition:

"""
    last(x)

Iterate through every element of the iterator `x` and return the last value iterated.
The default definition of `last` has O(n) time complexity, but some types might define
more efficient implementations.
"""

Note that I do not use the word "collection" anywhere, since there is no definition of "collection" in Julia.

We could have a separate method that reverses and then takes the first element, like this:

"""
    rlast(x)

Reverse the iterator `x`, iterate once, and return the value that was iterated.
Equivalent to `first(reverse(x))`. For types with efficient `reverse` methods,
this function has O(1) time complexity.
"""

Note that the semantics of last and rlast are different, in particular for stateful iterators and iterators with side effects.

Metadata

Metadata

Assignees

No one assigned

    Labels

    designDesign of APIs or of the language itselfiterationInvolves iteration or the iteration protocol

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions