Reputation: 11
I have list of lists like
ItemListData = [[1,"ABC","DEF",30],[2,"AXN","FOO",23],[3,"BDE","FO1",21],..]
and I would like to form list of records using record Item{ItemNo, Name, Description, quantity}
. Items list length would be varying. What would be the best way to create new list of records using ItemListData
.
Upvotes: 1
Views: 89
Reputation: 7158
Just use list_to_tuple:
rd(item, {num, name, descr, qty}),
Ls = [[1,"ABC","DEF",30],[2,"AXN","FOO",23],[3,"BDE","FO1",21]],
[list_to_tuple([item|L]) || L <- Ls].
Upvotes: 0
Reputation: 10252
You just need this:
rd(item, {num, name, descr, qty}).
L = [[1,"ABC","DEF",30],[2,"AXN","FOO",23],[3,"BDE","FO1",21]].
lists:map(fun([No, Name, Des, Qty]) -> #item{num = No, name=Name, descr=Des, qty=Qty} end, L).
Upvotes: 0
Reputation: 2496
@graymalkin's answer involves a lot of copying through the use of the ++
binary operator.
One should prefer list comprehensions here:
make_records(Records) ->
[#item{'#'=No, name=Name, descr=Descr, qty=Qty}
|| [No,Name,Descr,Qty] <- Records].
Edit: Use this function thusly: (in the shell)
1> rd(item, {'#', name, descr, qty}).
2> ItemListData = [[1,"ABC","DEF",30],[2,"AXN","FOO",23],[3,"BDE","FO1",21]].
3> some_module:make_records(ItemListData).
Upvotes: 1
Reputation: 51
Something like this would do...
make_records([], Records) -> Records;
make_records([[No,Name,Desc,Qty]|Xs], Records) ->
make_records(Xs, Records ++ Item{itemNo = No, name = Name, desc = Desc, qty = Qty}).
Upvotes: 0