I’ve put together a tiny package OneTwoMany.jl - that provides a function getsecond, as well as functions first_and_rest and first_second_rest.
Julia provides the functions first and last , but not second (except for Dates.second , which is about seconds in time). last can be used to access the second element of a Tuple with two elements or a Pair , but getsecond is clearer semantically. With tuples, it is also safer in cases where the upstream code that generates the tuple might change and generate longer tuples in the future.
The package is currently being registered. I couldn’t find a getsecond in any central lightweight package, but if this duplicates something similar, please let me know before registration is complete.
I’d say the first element of a collection is the one that is requested directly most often, if only a single element is accessed. Then the second one. After that, in my personal experience, direct access to only one element is less common. One doesn’t see x[3] or x[4] that much in code, compared to x[1] and x[2].
I’m a bit torn about this. On the one hand, users should expect getsecond(x) to do the same as x[2] (for collections with one-based indexing). On the other hand, retrieving whole unicode characters from strings is certainly more useful.
I agree, we should return the second element from a viewpoint of iteration for strings, not getindex(s,2).
help?> Iterators.peel
peel(iter)
Returns the first element and an iterator over the remaining elements.
If the iterator is empty return nothing (like iterate).
│ Julia 1.7
│
│ Prior versions throw a BoundsError if the iterator is empty.
See also: Iterators.drop, Iterators.take.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> (a, rest) = Iterators.peel("abc");
julia> a
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> collect(rest)
2-element Vector{Char}:
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
Base.tail is in the julia docs, doesn’t it mean the function is as official as it gets?
As for “generic”, maybe all it takes is someone making a PR to Julia extending tail to more types?