[erlang-questions] Maps and binaries

Hugo Mills hugo@REDACTED
Wed Dec 12 11:37:52 CET 2018


   Hi, Bob,

On Wed, Dec 12, 2018 at 10:24:35AM +0000, Bob Cowdery wrote:
> Its a long time since using Erlang so just getting back in. I know
> that there is always better ways to do things so is there a better
> patten matching way than this straight forward step-wise method.
> I have output from a UDP request put through jstone:decode which
> ends up like so:
> #{<<"outputs">> =>
>       [#{<<"api">> => <<"MME">>,<<"channels">> => 2,<<"direction">> => 1,
>          <<"index">> => 5,<<"name">> => <<"Microsoft Sound Mapper -
> Output">>},
>        #{<<"api">> => <<"MME">>,<<"channels">> => 8,<<"direction">> => 1,
>          <<"index">> => 6,<<"name">> => <<"Speakers (Realtek High
> Definiti">>},
> ...
>      #{<<"api">> => <<>>,<<"channels">> => 0,<<"direction">> => 0,
>          <<"index">> => 0,<<"name">> => <<>>}]}
> I want to extract the second member api and name.
> 
>     Map = jsone:decode(Resp),
>     List = maps:get(<<"outputs">>, Map),
>     Element = lists:nth(2, List),
>     Api = my_binary_to_list(maps:get(<<"api">>, Element)),
>     Dev = my_binary_to_list(maps:get(<<"name">>, Element)),
>     io:format("~p, ~p~n", [Api, Dev]).

   This seems perfectly reasonable as it is. However, you can
pattern-match maps this way:

   #{<<"outputs">> := List} = Map

and if you know that it's always going to be the second entry in the
list, you can pattern-match that with this:

   [_, Element | _] = List

   Note that with the map pattern, the key must always be either a
literal or a bound variable. Also note the required use of :=, which
is the "mandatory key" syntax, as opposed to =>, which is "optional
key". You can match multiple key/value pairs in a map in a single
pattern.

> my_binary_to_list(<<H,T/binary>>) ->
>     [H|my_binary_to_list(T)];
> my_binary_to_list(<<>>) -> [].

   Why not just use binary_to_list/1 in the erlang module?

   Hugo.

> prints:
> 
> "MME", "Speakers (Realtek High Definiti"
> 
> Thanks in advance, Bob
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-- 
Hugo Mills             | Doughnut furs ache me, Omar Dorlin
hugo@REDACTED carfax.org.uk |
http://carfax.org.uk/  |
PGP: E2AB1DE4          |                                            Steve Bell
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: Digital signature
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20181212/b8f880b7/attachment.bin>


More information about the erlang-questions mailing list