Reputation: 115
Can someone help me to understand this piece of Erlang code
to_price_file(Line, OutputFile) ->
Fields = csv:parse_line(Line),
[SupplierID, ProductCode, Description, DeliveryDate, CostPrice, UnitCount] = Fields,
Product = calculate_product(list_to_integer(SupplierID),list_to_integer(ProductCode),
Description, **date_utils:parse_date(DeliveryDate)**,
list_to_integer(CostPrice), list_to_integer(UnitCount)),
ok = write_pricefile(Product, OutputFile),
ok.
another sub-function parse_date (below) is called.
parse_date(DateString) ->
Tokens = string:tokens(DateString, "/"),
**[Year, Month, Day] = [list_to_integer(Str) || Str <- Tokens],
{Year, Month, Day}.**
I don't understand, what the commands in bold letters do in the sub-function.
Thanks, Anish
Upvotes: 0
Views: 109
Reputation: 20916
The function parse_date/1
assumes that the date string has the format "Year/Month/Day"
:
parse_date(DateString) ->
Tokens = string:tokens(DateString, "/"),
[Year, Month, Day] = [list_to_integer(Str) || Str <- Tokens],
{Year, Month, Day}.
It first calls string:tokens/2
which returns a list of the separate fields, "/"
is the separator string. It then does a list comprehension which for every element in Tokens
calls list_to_integer/1
and returns a list of the values. It then uses pattern matching to split the list into its separate parts and returns a tuple with the values. The values of the variables in an example run could be:
DateString = "2013/03/08"
Tokens = ["2013","03","08"]
[Year,Month,Date] = [2013,3,8]
{2013,3,8}
List comprehensions are quite common and often a very concise way of applying an operation to every element in a list, like lists:map/2
, with filtering options (not used here).
Note that in ISO standard the date should be written as 2013-03-08. :-)
Upvotes: 6