% 3723064
-module(t).
-export([record_sort/0, price_cmp/2, qty_cmp/2]).
-record (item, {id = 0, price = 0, quantity = 0}).
price_cmp(A, B) ->
A#item.price < B#item.price.
qty_cmp(A, B) ->
A#item.quantity < B#item.quantity.
record_sort() ->
Items = [
#item{id=1, price=10, quantity=5},
#item{id=2, price=50, quantity=0},
#item{id=3, price=30, quantity=3},
#item{id=4, price=60, quantity=9}
],
io:format("Unsorted Items: ~p~n", [Items]),
io:format("By Price: ~p~n", [lists:sort({t, price_cmp}, Items)]),
io:format("By Quantity: ~p~n", [lists:sort({t, qty_cmp}, Items)]).
% Alternatively use anonymous functions:
% io:format("By Price: ~p~n", [lists:sort(
% fun(A, B) -> A#item.price < B#item.price end, Items)]),
%
% io:format("By Quantity: ~p~n", [lists:sort(
% fun(A, B) -> A#item.quantity < B#item.quantity end, Items)]).
This will yield (assuming example file t.erl
):
1> c(t).
{ok,t}
2> t:record_sort().
Unsorted Items: [{item,1,10,5},{item,2,50,0},{item,3,30,3},{item,4,60,9}]
By Price: [{item,1,10,5},{item,3,30,3},{item,2,50,0},{item,4,60,9}]
By Quantity: [{item,2,50,0},{item,3,30,3},{item,1,10,5},{item,4,60,9}]
ok