gpt4 book ai didi

database - 如何在 Erlang 中更新 Mnesia 表

转载 作者:太空狗 更新时间:2023-10-30 01:55:07 24 4
gpt4 key购买 nike

我的代码有点问题。我有一个包含汽车详细信息、名称、价格和数量的表格,因此我试图创建一个名为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com