Dynamic variable assignment by recursion or loop?

Richard O'Keefe raoknz@REDACTED
Sat Jul 4 09:04:36 CEST 2020


foldr_tuple(F, A, Tuple) ->
    foldr_tuple_loop(F, A, Tuple, N).

foldr_tuple_loop(_, A, _, 0) ->
    A;
foldr_tuple_loop(F, A, Tuple, K) ->
   foldr_tuple_loop(F, F(A, element(K, Tuple)), Tuple, K-1).

Stick that in a library somewhere; if you are working with
variable-length tuples you'll have other uses for it.

    foldr_tuple(fun (S, L) ->
            [string:len(S), [[C] || C <- S] | L]
        end, [], Input)

Of course you can combine tuple_to_list/2 and lists:foldr/3,
but this avoids creating an intermediate list that you do not
really want.




On Fri, 3 Jul 2020 at 21:36, Papa Tana <papa.tana101@REDACTED> wrote:

> Hi World,
>
> I have the below code working very well:
>
> Input = {"DUMMYAPN", "MNC005", "MCC646", "GPRS"}.
>
> Static1 = element(1,Input).
> Static2 = element(2,Input).
> Static3 = element(3,Input).
> Static4 = element(4,Input).
>
> Size1 = string:len(Static1).
> Size2 = string:len(Static2).
> Size3 = string:len(Static3).
> Size4 = string:len(Static4).
>
> Ret1 = [[X] || X <- Static1].
> Ret2 = [[X] || X <- Static2].
> Ret3 = [[X] || X <- Static3].
> Ret4 = [[X] || X <- Static4].
>
> VALUE = [Size1, Ret1,Size2, Ret2,Size3, Ret3,Size4, Ret4].
> BINARYVALUE = list_to_binary([Size1, Ret1,Size2, Ret2,Size3, Ret3,Size4,
> Ret4]).
>
> Expected Result is Ok:
> [8,
>  ["D","U","M","M","Y","A","P","N"],
>  6,
>  ["M","N","C","0","0","5"],
>  6,
>  ["M","C","C","6","4","6"],
>  4,
>  ["G","P","R","S"]]
>
> <<8,68,85,77,77,89,65,80,78,
>         6,77,78,67,48,48,53,
>         6,77,67,67,54,52,54,
>         4,71,80,82,83>>
>
>
> The problem is that the Input value does not always have the same
> format, and changes everytime, for example:
> Input = {"TOPON", "S11", "NODE", "EPC", "MNC05", "MCC646",
> "3GPPNETWORK", "ORG"}.
>
>
> My problem is:
> I am creating N variables each time I receive an Input with Length of N.
> I'm sure that there is a more efficient way to work with it, by using
> kind of loop or recursion, but I'm stuck a couple of days so far, I
> cannot find how to achieve it.
> Any advice would be welcome.
>
> Thanks,
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20200704/d0a71d6c/attachment.htm>


More information about the erlang-questions mailing list