7stud
Updating a map's values that are lists
What is the Elixir equivalent to Ruby’s Hash.new where you can specify a block that returns an empty list when you access a non-existent key (or Perl’s autovivification feature)?
The idea is that when you access a key in a Map that doesn’t exist you get back an empty list, which you can then append values to. And, if the key does exist, then you get back a non-empty list, which you can also append values to.
Also, why is it that the editor for this forum has a textbox that says “choose optional tags for this topic”, yet when I submit my question, I get an alert that says “You must choose at least 1 tag”, yet none of the tags are relevant to my question?
Most Liked
sribe
Elixir is not Perl. The phrase “if you treat a value returned by a key as a list” makes no sense in the Elixir context–you’re basically saying “if you expect of type XXX and you get nil, then automagically create an XXX and substitute it”, and that is exactly the kind of implicit magic that Elixir tries to avoid, by design.
AstonJ
We generally don’t use ‘elixir’ as a tag since pretty much everything is related to Elixir on this forum
(and so I’ve made it a staff only tag)
I’ve added maps and lists as tags as they seem most relevant ![]()
sribe
Don’t confuse syntactic sugar and implicit magic–the examples you post are all completely explicit.
peerreynders
irb(main):001:0> h = Hash.new {|hash, key| hash[key] = []}
=> {}
irb(main):002:0> h.has_key?(:a)
=> false
irb(main):003:0> h[:a]
=> []
irb(main):004:0> h.has_key?(:a)
=> true
irb(main):005:0> g = Hash.new([])
=> {}
irb(main):006:0> g.has_key?(:a)
=> false
irb(main):007:0> g[:a]
=> []
irb(main):008:0> g.has_key?(:a)
=> false
irb(main):009:0>
I think it needs to be said that Hash is an object - where behaviour and data are complected (possibly even on the instance level) - while Map is a data structure where the Map module provides the necessary functions to consistently manipulate that data structure.
So with Maps custom behaviour is either accomplished by injecting custom behaviour (under the control of the user of the data structure) functions like the Access.key/2 example or by defining new new manipulation functions as part of a new module - possibly creating a new data structure altogether that the standard Map becomes a part of.
OvermindDL1
In functional languages that kind of access is ‘inverted’, you specify the default arguments on the calls instead of the object, thus:
iex(1)> m = %{}
%{}
iex(2)> Map.get(m, :nope, [])
[]
iex(3)> Map.update(m, :nope, [6.28], &[ 6.28 |&1])
%{nope: [6.28]}
Which of course you can wrap up as new calls in your own custom module. ![]()
Or do something generic like make a DefaultMap module that delegates to the normal Map module but sets an override default key in the map or something.
Lots of options. ![]()
A relevant tag would just be ‘elixir’ or so, but adding tags is a good way to be able to search for topics in the future. ![]()







