如何在erlang中修改记录?

时间:2010-04-26 17:32:18

标签: erlang record immutability

我需要修改操作记录中的{place}和{other_place}值。

#op{
    action   = [walk, from, {place}, to, {other_place}],
    preconds = [[at, {place}, me], [on, floor, me], 
                [other_place, {place}, {other_place}]],
    add_list = [[at, {other_place}, me]],
    del_list = [[at, {place}, me]]
}

但是erlang不允许修改变量。是否有数据类型?

1 个答案:

答案 0 :(得分:20)

erlang不允许您修改变量。但没有什么可以阻止你修改变量的副本。

鉴于你的记录:

Rec = #op{
    action   = [walk, from, {place}, to, {other_place}],
    preconds = [[at, {place}, me], [on, floor, me], 
                [other_place, {place}, {other_place}]],
    add_list = [[at, {other_place}, me]],
    del_list = [[at, {place}, me]]
}

您可以像这样有效地获得修改后的版本:

%% replaces the action field in Rec2 but everything else is the same as Rec.
Rec2 = Rec#op{action = [walk, from, {new_place}, to, {new_other_place}]}

这将完成你似乎要问的事情。