Hi,

I propose adding an `Access.at!` that raises when the given index is out of 
bounds, analogous to `Access.key!`.

The current `Access.at` is not nil safe as discussed in 
https://groups.google.com/g/elixir-lang-core/c/CvdW1FsvSf0/m/nlvxkThuEwAJ, 
but it's also not analogous to `Access.key!`. 

I specifically want it to raise and point to being out of range (or 
whatever the terminology is), rather than causing nil errors further down 
the line.

Current behaviour with `Access.at`:

# Happy case. Everything exists.
iex(20)> get_in([%{key: "value"}], [Access.at(0), :key])
"value"

# Nil safe when index is out of bounds.
iex(21)> get_in([%{key: "value"}], [Access.at(1), :key])
nil

# Not nil safe, but error doesn't point to the array index.
iex(22)> get_in([%{key: "value"}], [Access.at(1), Access.key!(:key)])
** (RuntimeError) Access.key!/1 expected a map/struct, got: nil
    (elixir 1.10.3) lib/access.ex:514: anonymous fn/4 in Access.key!/1

I propose something like this behaviour, with `Access.at!`:

# Happy case – behaves the same.
iex(20)> get_in([%{key: "value"}], [Access.at!(0), :key])
"value"

# Explodes.
iex(21)> get_in([%{key: "value"}], [Access.at!(1), :key])
** (FooError) index 1 not found in: [%{key: "value"}]. Its highest index is 
0.

# Explodes in the same way.
iex(22)> get_in([%{key: "value"}], [Access.at(1), Access.key!(:key)])
** (FooError) index 1 not found in: [%{key: "value"}]. Its highest index is 
0.

What do you think?

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/3a5d1489-dfa5-4c0c-bcd1-5cb85eac2f3fn%40googlegroups.com.

Reply via email to