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 or x that much in code, compared to x and x.
I’m a bit torn about this. On the one hand, users should expect getsecond(x) to do the same as x (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).
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.
julia> (a, rest) = Iterators.peel("abc");
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)