Re: Binary String pattern matching

Andreas Schultz <[email protected]>
Newsgroups gmane.comp.lang.erlang.general
Message-ID <CAC=ZbaTvPg-f3OJnAmNi8rQwUByVO-XMwajD40uByznSCu3E1A@mail.gmail.com>
Hi,

Short version without input validation, will crash if the input does not
match the expected values:

currency(<<"CHF">>) -> chf;
currency(<<"EUR">>) -> eur;
currency(<<"US">>) -> us.

currrency_to_credits({cur, String}, Acc) ->
    {Value, Currency} = string:to_integer(String),
    {currency(Currency), Acc + Value}.

Andreas

Am Mi., 9. Dez. 2020 um 19:49 Uhr schrieb Java House <[email protected]>:

> there is a typo in the example
> currrency_to_credits({cur, << Value , "CHF">>}, Acc)
>   when Value >= <<"1000">>, Value =< <<"10000">> ->
>      {chf, Acc + Value };
> currrency_to_credits({cur, << Value , "EUR">>}, Acc)
>   when Value >= <<"1000">>, Value =< <<"10000">> ->
>      {eur, Acc + Value };
> currrency_to_credits({cur, << Value , "US">>}, Acc)
>   when Value >= <<"1000">>, Value =< <<"10000">> ->
>      {us, Acc + Value };
>
> Στις Τετ, 9 Δεκ 2020 στις 7:17 μ.μ., ο/η Java House <[email protected]>
> έγραψε:
>
>> Hello all
>>
>> I am learning Erlang and have stuck to the following problem.
>> How to write a function with pattern matching when the parameter is a
>> binary string.
>>
>> I have a list of binary strings e.g.
>> <<3123CHF>>
>> <<341424343EUR>>
>> <<14143US>>
>>
>> I am trying to create a function that matches according to a pattern.
>>
>> currrency_to_credits({cur, <<A, "CHF">>}, Acc)
>>   when Value >= <<"1000">>, Value =< <<"10000">> ->
>>      {chf, Acc + A};
>> currrency_to_credits({cur, <<A, "EUR">>}, Acc)
>>   when Value >= <<"1000">>, Value =< <<"10000">> ->
>>      {eur, Acc + A};
>> currrency_to_credits({cur, <<A, "US">>}, Acc)
>>   when Value >= <<"1000">>, Value =< <<"10000">> ->
>>      {us, Acc + A};
>>
>> But this does not seem to be the right way.
>> How can I create a pattern for binary string?
>> will it work better for list string? How?
>>
>> Thank you
>> Nikolas
>>
>

-- 

Andreas Schultz

-- 

Principal Engineer

t: +49 391 819099-224

------------------------------- enabling your networks
-----------------------------

Travelping GmbH
Roentgenstraße 13
39108 Magdeburg
Germany

t: +49 391 819099-0
f: +49 391 819099-299

e: [email protected]
w: https://www.travelping.com/
Company registration: Amtsgericht Stendal
Managing Director: Holger Winkelmann
Reg. No.: HRB 10578
VAT ID: DE236673780
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.