Skip to content

Access protocol for all lists of tuples #611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/elixir/lib/access.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,13 @@ defimpl Access, for: List do

"""

def access(list, atom) when is_atom(atom) do
Keyword.get(list, atom)
def access([], _key), do: nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it make sense to keep a special atom clause for Keyword here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? It's just an extra function call.

Let's try to keep access as fast as possible.


def access(list, key) do
case :lists.keyfind(key, 1, list) do
{ ^key, value } -> value
false -> nil
end
end

end
Expand Down
3 changes: 3 additions & 0 deletions lib/elixir/test/elixir/access_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ defmodule AccessTest do
assert [foo: :bar][:foo] == :bar
assert [foo: [bar: :baz]][:foo][:bar] == :baz
assert [foo: [bar: :baz]][:fuu][:bar] == nil
assert [{"foo", :bar}]["foo"] == :bar
assert [{"foo", [{"bar", :baz}]}]["foo"]["bar"] == :baz
assert [{"foo", [{"bar", :baz}]}]["fuu"]["bar"] == nil
end

test :nil do
Expand Down