Comments (4)
I actually think that a function such as nth(itr,n)
is more of an endpoint in the lifetime of an iterator.
Therefore, when you are calling nth
you get the end result and not the continuation of the iterator. Plus it matched the intuitive action of "get me the nth element", without forcing the user to deal with the rest
or status
at every callsite of the nth
function. Following a bit the principle of least surprise.
For many intents and purposes, I see nth(itr, n)
as a generalisation of the first(itr)
function in Base
:
nth(itr, n) = begin
y = iterate(Base.Iterators.drop(itr, n-1))
ifelse(isnothing(y), nothing, getindex(y, 1))
end
function first(itr)
x = iterate(itr)
x === nothing && throw(ArgumentError("collection must be non-empty"))
x[1]
end
# it could become just this
# (not backward compatibile and slower, i know, it's just to showcase)
first(itr) = nth(itr, 1)
in my opinion the number of lines of code shouldn't matter when talking about APIs, if it's just a one-liner all the better, but it shouldn't be a justification for not putting something in, just for reference, this is the implementation of first(itr, n)
and last(itr, n)
in Base
:
first(itr, n::Integer) = collect(Iterators.take(itr, n))
last(itr, n::Integer) = reverse!(collect(Iterators.take(Iterators.reverse(itr), n)))
from julia.
I just note that
_safe_nth(itr, n) = begin
y = iterate(Base.Iterators.drop(itr, n-1))
ifelse(isnothing(y), nothing, getindex(y, 1))
end
is as fast as your _inbounds_nth
.
julia> @btime _safe_nth(itr, 9999) setup=(itr=collect(1:10000))
161.977 ns (0 allocations: 0 bytes)
9999
Actually I'm a bit confused by the fact that the normal branching has a so high cost.
from julia.
That is great, didn't know about ifelse
!
The performance disparity might be due to the fact that ifelse
is a normal function call, so it evaluates all arguments beforehand which might help with eliminating the branching altogether?
At this point there isn't really a reason to have a "safe" and "unsafe" version. might as well always check for nothing
and have the best of both worlds.
from julia.
Actually I think the performance gain is just some kind of edge case optimization, consider this with your original version:
julia> itr = Iterators.filter(x -> x != 10, 1:10000);
julia> @btime _inbounds_nth($itr, 9999);
7.086 μs (0 allocations: 0 bytes)
julia> @btime _safe_nth($itr, 9999);
7.083 μs (0 allocations: 0 bytes)
In any case I think that returning only the element and not a new iterator starting from there is not ideal because usually one wants to go on with the iteration afterwards so I would consider something like:
julia> nth(itr, n) = Iterators.peel(Iterators.drop(itr, n-1))
julia> @btime nth($itr, 9999);
7.086 μs (0 allocations: 0 bytes)
but at the same time it is just a one-liner so I'm not sure it is worth it
from julia.
Related Issues (20)
- `MethodError: no method matching active_module()` (leading to world age error), on Julia 1.11 HOT 5
- bugs involving `IdentityUnitRange` HOT 2
- `getindex` and `isassigned` with big `BigInt` ranges and trailing 1 indices errors HOT 2
- `const` before destructuring is inconsistent
- Source build of 1.12.0 on macOS ARM: failure of Pkg repl prompt after `3fc35778cc` HOT 2
- Add 2-arg `include` `mapexpr` to cache header?
- Feature Request: Add Syntactic Sugar for Compile-Time Constants in Function Definitions HOT 5
- Problem with `isfile_casesensitive()` on Windows HOT 1
- exit_current_timer implementation is unsound HOT 1
- export statement lowering correctness, causing regression HOT 5
- sleep_state not_sleeping is not reset as required by signals
- [Test] need shim for FieldError HOT 1
- Julia builds for `native` CPU, even with `XC_HOST = x86_64-w64-mingw32` HOT 2
- Performance regressions in linear algebra benchmarks with Hermitian and Triangular matrices
- Performance regressions in BaseBenchmarks due to #54647 (Cleanup `MemoryRef`) HOT 2
- observed failure of TestPkg thread test
- race condition in waitany test
- Regression in threads tests on FreeBSD
- Operations on `views` much slower when indices are `start:1:stop` HOT 7
- [1.11+] jl_array_t no longer contains elsz HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from julia.