作爲學習Erlang的練習,我試圖編寫一個簡單的數據庫(來自O'Reilly編程Erlang)。試圖在Erlang中列出問題的問題
基本上我有這樣的元組的列表:
Db1 = [{person1,charleston},{person2,charleston},{person3,chicago}].
我需要創建功能,使得
db:match(charleston,Db1).
回報
[person1,person2]
下面是我寫的方法:
match(Element, Db) -> match(Element, Db, []).
match(_Element,[], Results) -> Results;
match(Element, [{Key,Value}|T], Results) ->
case Value == Element of
true -> match(Element, T, [Results,Key]);
false -> match(Element,T,Results)
end.
我找回結果是這樣的:
[[[],person1],person2]
我知道有名單與lists.erl
模塊相結合的方式,但我試圖繞過它在努力瞭解更多有關語言。任何想法我做錯了什麼?
您的'案件值==元素'可以摺疊到子句中:match(Value,[{Key,Value} | T],...) - >'等等。 – 2011-02-28 13:37:11
你的情況很簡單我不會在這裏使用尾遞歸累加器,而是使用'[Key | match(Element,T)]'作爲遞歸器。 – 2011-02-28 13:38:44