Chris
Chris

Reputation: 12181

Erlang Split a Tuple

I want to call map on a dict and get a list of their values back. Erlang doesn't have that built into the dict module, so here is how I'm getting around that:

Fn = fun(Tuple) ->
  [Key, Value] = Tuple,
  string:join([Key, Value], "=")
end,
lists:map(Fn, dict:to_list(Dict)).

The problem is that Key and Value are then getting assigned multiple times. How can I "split" the key/value tuple that is returned by dict:to_list inside of the anonymous function's call to string:join?

Upvotes: 0

Views: 1580

Answers (3)

macintux
macintux

Reputation: 894

Relative newcomer who's never tackled the dict module before, but this seems to work for me:

dict:fold(fun(Key, Value, Accum) ->
                  [Value | Accum] end, [], D).

Example:

init() ->
    Dict = dict:new(),
    Dict2 = dict:append(key, value, Dict),
    Dict3 = dict:append(key2, value2, Dict2),
    dict:append(key3, value3, Dict3).

grab_values(D) ->
    dict:fold(fun(Key, Value, Accum) ->
                      [Value | Accum] end, [], D).

Invoked:

4> D = dictfold:init().
{dict,3,16,16,8,80,48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],[],
        [[key2,value2]],
        [[key3,value3]],
        [],[],[],[],[],
        [[key,value]],
        [],[],[],[],[],[]}}}
5> dictfold:grab_values(D).
[[value2],[value3],[value]]

Upvotes: 1

chops
chops

Reputation: 2612

I'm not sure I'm following what you're asking here. What do you mean by "Key and Value are assigned multiple times"?

When you say that you want to map over the dict and get a list of values back, do you mean values in the "Key-Value" sense? In which case, you could do a this:

Values = [V || {_,V} <- dict:to_list(Dict)].

Which would just give you a list of the "value" side of the Key-Value nature of the dict.

You could also just get a list of keys by doing something similar.

Keys = [K || {K,_} <- dict:to_list(Dict)].

If you just want lists both Key and Values separated, you could use lists:unzip/1.

{Keys, Values} = lists:unzip(dict:to_list(Dict)).

Then Keys would be a list of all the keys, and Values would be a list of all the values.

Or are you concerned with the fact that Key and Value are both being assigned (as in variable assignment) for each member of your dict? If so, don't. Those assignments are fast and are just pointers, not memory copies.

Upvotes: 2

Gabriel Kastenbaum
Gabriel Kastenbaum

Reputation: 31

As you have a list of tuples with a lists as values maybe you're looking somthing like this:

[string:join ([K, V], "=") || {K, Values} <- dict:to_list(Your_dictionary), V <- Values].

Hope this helps

Upvotes: 3

Related Questions