Dynamic variable assignment by recursion or loop?

Hugo Mills hugo@REDACTED
Fri Jul 3 11:43:22 CEST 2020


On Fri, Jul 03, 2020 at 12:36:06PM +0300, Papa Tana 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.

   There's a tuple_to_list/1 function. Use that to start with, and
then you can map over the list to generate a list of size/value
binaries, converting one at a time. Then finally fold over that list
to produce the final binary.

   Alternatively, require the input to be a list in the first place,
and you can skip the tuple_to_list/1 part. (But the rest is still
necessary).

   Hugo.

-- 
Hugo Mills             | Well, sir, the floor is yours. But remember, the
hugo@REDACTED carfax.org.uk | roof is ours!
http://carfax.org.uk/  |
PGP: E2AB1DE4          |                                             The Goons


More information about the erlang-questions mailing list