2013-01-18 37 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(你說這不是一個選項)或 - 你可以放在列表的前面|運營商。