How do I save a non-trivial value to an attribute in Elixir? -
so understand when defining attributes module in elixir syntax @myvariable 30 however, in case let's module defined follows:
defmodule mymodule def add(x,y), do: x + y @myvariable add(3,4) def print, do: @myvariable end ideally should print out 7, compileerror: undefined function add/2
in specific case, value want store attribute large map not trivial add(3,4) i'm pretty sure same concept applies. if attributes not correct way go this, please let me know real "elixir" way go is.
in case, i want able access keys of map throughout module instead of having pass whole map parameter each function.
thanks!
@values not variables, module attributes. not stored in module default , value exists during compile-time. elixir 'getting started' guide:
module attributes in elixir serve 3 purposes:
- they serve annotate module, information used user or vm.
- they work constants.
- they work temporary module storage used during compilation.
the problem code @myvariable being set during compilation of mymodule add(3, 4) can't calculated since module hasn't been compiled yet.
the simplest solution define add(x, y) in module , call there:
defmodule othermodule def add(x, y), do: x + y end defmodule mymodule @myvariable othermodule.add(3, 4) def print, do: @myvariable end you can similarly define map module attribute, after compilation become constant won't able modify (which guess want).
Comments
Post a Comment