我想显示产品记录列表的价格范围。
假设我有这个产品清单,其中包含金额/价格的二进制值。
Products = [#product{amount=<<"20.21">>}, #product{amount=<<"30.21">>}, #product{amount=<<"9.21">>}]
我的目标是显示最小 - 最大价格范围,例如: &LT;&LT; “9.21” &GT;&GT; - &lt;&lt;“30.21”&gt;&gt;
怎么可以在这里继续?
答案 0 :(得分:3)
-module(my).
-compile(export_all).
-record(product, {name, price}).
products() ->
[
#product{name='a', price= <<"20.21">>},
#product{name='b', price= <<"30.21">>},
#product{name='c', price= <<"9.21">>},
#product{name='d', price= <<"11.21">>}
].
price_range(Products) ->
PriceFunc = fun(Product, {Min, Max}) ->
Price = binary_to_float(Product#product.price),
NewMin = min(Min, Price),
NewMax = max(Max, Price),
{NewMin, NewMax}
end,
InitPrice = binary_to_float(
(hd(Products))#product.price
),
lists:foldl(PriceFunc, {InitPrice, InitPrice}, Products).
在shell中:
9> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
10> Products = my:products().
[{product,a,<<"20.21">>},
{product,b,<<"30.21">>},
{product,c,<<"9.21">>},
{product,d,<<"11.21">>}]
11> my:price_range(Products).
{9.21,30.21}