Reputation: 308
I have a tuple generated using jiffy library.
For example : jiffy:decode(<<"{\"foo\":\"bar\"}">>).
results in
{[{<<"foo">>,<<"bar">>}]}
I want <<"foo">>
to be "foo"
Is there a way for converting the <<"foo">>
to "foo"
?
Basically I want to convert this:
[{<<"t">>,<<"getWebPagePreview">>},{<<"message">>,<<"google.com">>}]
into this:
[{"t",<<"getWebPagePreview">>},{"message",<<"google.com">>}]
note: consider this to be a very large list, and I want an efficient solution.
Upvotes: 3
Views: 262
Reputation: 26121
Because (when) order of elements doesn't matter the most efficient version is
convert({List}) ->
{convert(List, [])}.
convert([], Acc) -> Acc;
convert([{X, Y}|T], Acc) ->
convert(T, [{binary_to_list(X), Y}|Acc]).
When you want to preserve order of element strightforward version with list comprehension
convert({List}) ->
{[{binary_to_list(X), Y} || {X, Y} <- List]}.
is the (almost) exact equivalent of
convert({List}) ->
{convert_(List)}.
convert_([]) -> [];
convert_([{X, Y}|T]) ->
[{binary_to_list(X), Y}|convert_(T)].
Upvotes: 2
Reputation: 14042
there is a function to transform a binary <<"hello">>
into a list "hello"
:
1> binary_to_list(<<"hello">>).
"hello"
2> L = [{<<"t">>,<<"getWebPagePreview">>},{<<"message">>,<<"google.com">>}].
[{<<"t">>,<<"getWebPagePreview">>},
{<<"message">>,<<"google.com">>}]
You can apply this to your list using a list comprehension:
3> [{binary_to_list(X),Y} || {X,Y} <- L].
[{"t",<<"getWebPagePreview">>},{"message",<<"google.com">>}]
4>
you can embed this in a function:
convert(List) ->
F = fun({X,Y}) -> {binary_to_list(X),Y} end,
[F(Tuple) || Tuple <- List].
Upvotes: 4