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!
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!
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.
Alright, thank you. Indeed the imaginary function would probably return a tuple so the overhead is minimal.
My use case is I have data like this:
[
fruit: [
"banana",
"apple"
],
instrument: [
"banjo"
]
]
And I build a suffix tree like that:
%{
"a" => %{"p" => %{"p" => %{"l" => %{"e" => %{values: [fruit: "apple"]}}}}},
"b" => %{
"a" => %{
"n" => %{
"a" => %{"n" => %{"a" => %{values: [fruit: "banana"]}}},
"j" => %{"o" => %{values: [instrument: "banjo"]}}
}
}
}
}
And I want to benchmark a possible optimization, so I turn the tree into this:
%{
["a", "p", "p", "l", "e"] => %{values: [fruit: "apple"]},
["b", "a", "n"] => %{
["a", "n", "a"] => %{values: [fruit: "banana"]},
["j", "o"] => %{values: [instrument: "banjo"]}
}
}
To see if retrieval is gonna be faster. But I can only merge the suffix if the sub map has only one key.
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: ...}}
}
}
}
Well I want to match any part of the word. For instance "an"
would match "banana"
and "banjo"
, "ae"
would match "apple"
so I am not sure I can avoid searching in the list if the map key is a list.