So first
is an extremely useful function, and so is last
.
Some languages, like rails, even have a second()
function. This has led to some controversy on the subject:
What is the best way to define all the numbers from two to one thousand as functions that grab indices from arrays?
This might help a little?
For the record, I think this is a terrible idea and nobody should do it. But, jut for fun
nthlist = ["first", "second", "third", "fourth", "fifth"]
for (n, nth) ∈ enumerate(Symbol.(nthlist))
isdefined(@__MODULE__, nth) && continue
@eval $nth(v) = v[$n]
end
Of course, you’d have to do a little bit of English and string manipulation to generat nthlist
. If you can find an existing list you’d be all set. It wouldn’t be hard to extend this to general iterators that don’t support indexing.
Seriously though, don’t do it.
3 Likes
Ah, the obviousness of 0-based indexing:
10 Likes
Wow, I’ve gotten so used to multiple dispatch that I stared at that code snippet for a few minutes in complete puzzlement before I realized what it meant. This coming from someone with about 8 years of mostly C++.
Obviously, you need to start with zeroth
!
2 Likes
FWIW, coming from Common Lisp I originally missed first
, …, tenth
, but now I think that
- In the (rare) cases I need it,
x -> x[n]
is more readable and should compile equally efficiently now (for a constant n
),
- More generally, using accessors like this encourages bad coding habits as it forces the user to remember the layout. This is a reasonable compromise for 2 elements, but for anything more, we have
NamedTuple
s (which are lightweight and yet optimized, ideal for most cases), composite types (for something you use more extensively), Dict
s (for a heterogeneous number of elements), etc.