2013-01-18 35 views
0

我想将元素追加到列表中,并且我不允许使用列表库或任何其他BIF。我怎么想它的一个例子是:将元素追加到没有Erlang中的列表库模块的列表中

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}] 

我理解的错误消息,但我不知道如何从这里走......

回答

2

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

+1

修好了!问题不在于我的解决方案,就像你说的,Db2已经被分配了一个值,并且在重新启动shell时,它工作正常!感谢legoscia! –

2

您可以通过List ++ [Element]

1

与++运算符追加追加元素到列表中不是很推荐。你只能在小列表中使用它。

你有两个选择: - 列表:append(你说这不是一个选项)或 - 你可以放在列表的前面|运营商。