Reputation: 145
I am trying to implement the Modbus protocol in Elixir as an exercise to learn Elixir and to further my understanding of Functional Programming.
Modbus data is modeled as contiguous blocks of registers. A modbus read request takes the form of . This instructs the server to collect the registers starting at and continuing up for registers. For example, if was 0 and was 5, the server would return the values of registers 0, 1, 2, 3, and 4.
I am thinking that a good data structure for modeling these registers is a map where the key is the register and the value is the value of the register. Therefore, I am curious if there is an idiomatic way to retrieve multiple values from a map given multiple keys, without having to iterate through the keys and calling get() for each key.
I would be open to other suggestions for a better data model, if the map isn't really appropriate.
Python has itemgetter in the operator module to perform this task. Maybe that will give another clue for what I am trying to accomplish.
Upvotes: 4
Views: 5967
Reputation: 121000
Map#take/2
would do:
iex(1)> data = %{a: 42, b: 3.14, foo: :bar}
iex(2)> data |> Map.take(~W|a foo|a)
%{a: 42, foo: :bar}
On the other hand, your data looks and quacks more like Keyword
list:
iex(3)> data = [a: 42, b: 3.14, foo: :bar]
iex(4)> data |> Keyword.take([:a, :foo])
[a: 42, foo: :bar]
It’s up to you to pick any of above, or even provide your own struct with handy methods to retrieve subsets.
Upvotes: 16