在Erlang中没有列表库模块的情况下将元素附加到列表中

时间:2013-01-18 13:45:27

标签: list erlang

我想将元素附加到列表中,我不允许使用列表库或任何其他BIF。我想要它的一个例子:

Eshell V5.9.1 (abort with ˆ G)
1> Db = db:new().
[]
2> Db1 = db:write(apple, fruit, Db).
[{apple,fruit}]
3> Db2 = db:write(cucumber, vegetable, Db1).
[{apple,fruit},{cucumber,vegetable}]

我现在的代码(不工作):

write(Key, Element, []) -> [{Key, Element}|[]];
write(Key, Element, [H|T]) -> [H|write(Key,Element,T)].

我得到的错误是我这样做的时候:

3> Db2 = db:write(cucumber, vegetable, Db1).
** exception error: no match of right hand side value [{apple,fruit},{cucumber,vegetable}]

我理解错误信息,但我不知道如何离开这里...

3 个答案:

答案 0 :(得分:2)

我怀疑这只是Db2已经有一个值的情况,它与db:write的返回值(根据错误消息[{apple,fruit},{cucumber,vegetable}]的值不同)。键入Db2.以查看其具有的值,并键入f(Db2).以“忘记”其值,以便您可以再次为其分配。

答案 1 :(得分:2)

您可以通过List ++ [Element]

将元素追加到列表中

答案 2 :(得分:1)

不建议使用++运算符追加。您只能将它用于小列表。

您有两种选择: - 列表:追加(你说它不是一个选项)或 - 您可以使用|列表放在列表前面操作

相关问题