我的代码有点问题。我有一个包含汽车详细信息、名称、价格和数量的表格,因此我尝试创建一个名为 buy
的函数,该函数将用于购买特定汽车。当用户购买例如 5 辆 BMW 汽车时,他们将调用 buy_car(bmw,5)
。在此之后,我想更新 BMW 汽车数量的新值。
我的尝试如下,但我似乎无法解决它,我是 Erlang 的新手。
buy_car(X,Ncars) ->
F = fun() ->
%% ----first i find the number of car X available in the shop
[Xcars] = mnesia:read({car,X}),
Nc = Xcars#car.quantity,
Leftcars = Xcars#car{quantity = Nc - Ncars},
%% ---now we update the database
mnesia:write(Leftcars),
end,
mnesia:transaction(F).
请帮助我如何编写从商店购买汽车的功能。
最佳答案
但是您的实现工作正常,除非您在 mnesia:write(Leftcars) 之后添加了非法逗号。
这是有效的代码(我尝试将您的实现作为buy_car2)。
-module(q).
-export([setup/0, buy_car/2, buy_car2/2]).
-record(car, {brand, quantity}).
setup() ->
mnesia:start(),
mnesia:create_table(car, [{attributes, record_info(fields, car)}]),
mnesia:transaction(fun() -> mnesia:write(#car{brand=bmw, quantity=1000}) end).
buy_car(Brand, Ncars) ->
F = fun() ->
[Car] = mnesia:read(car, Brand), % crash if the car is missing
mnesia:write(Car#car{quantity = Car#car.quantity - Ncars})
end,
mnesia:transaction(F).
buy_car2(X,Ncars) ->
F = fun() ->
%% ----first i find the number of car X available in the shop
[Xcars] = mnesia:read({car,X}),
Nc = Xcars#car.quantity,
Leftcars = Xcars#car{quantity = Nc - Ncars},
%% ---now we update the database
mnesia:write(Leftcars)
end,
mnesia:transaction(F).
关于database - 如何在 Erlang 中更新 Mnesia 表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9551407/