lud
Is there a way to retrieve the single key/value in a map?
When you know that the map has only one key (from a guard for instance), is there something more efficient than this:
[{k, v}] = Map.to_list(map)
Thank you!
Most Liked
zachallaun
To my knowledge, no, and what you have there will be about as efficient as you can get (you have to construct a tuple in order to return the key/value pair, so the overhead is essentially a single cons cell for the list).
I’d be curious to know a bit more about the use-case, though. I’m having trouble thinking of a case where it makes sense to use a map to contain a single key/value pair.
zachallaun
Got it!
You’re losing constant-time lookup that way, though, as you now have to scan the map to match the first character. It’ll probably be negligible for small trees but could be more significant for trees with many character prefixes.
You might consider a structure like this:
%{
"a" => {["p", "p", "l", "e"], %{value: ...}},
"b" => {
["a", "n"],
%{
"a" => {["n", "a"], %{value: ...}},
"j" => {["o"], %{value: ...}}
}
}
}
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









