3

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.

Tad Lispy
  • 2,806
  • 3
  • 30
  • 31
Mandeep Singh
  • 308
  • 2
  • 5
  • 18

2 Answers2

4

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].
Pascal
  • 13,977
  • 2
  • 24
  • 32
  • Is it the best way we can do this? Since the string is very large, I'm concerned about efficiency. Is there any other way, like using c language in combination with Erlang? or any other way? – Mandeep Singh Jan 30 '17 at 17:48
2

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)].
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
  • Is it the best way to do this? I'm concerned about efficiency of solution because string is very large. – Mandeep Singh Jan 30 '17 at 17:49
  • 2
    For such example you can benchmark the different solutions: `timer:tc(module_name,convert_method,[List])`. But yes you will not find faster solutions. – Pascal Jan 30 '17 at 18:17