【发布时间】:2011-07-05 13:06:42
【问题描述】:
作为学习 Erlang 的练习,我正在尝试编写一个简单的数据库(来自 O'Reilly 的 Programming 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 模块结合起来,但我试图绕过它以了解更多关于该语言的信息。任何想法我做错了什么?
【问题讨论】:
-
你的
case Value == Element可以折叠成子句:match(Value, [{Key, Value}|T], ...) ->等等。 -
你的情况很简单,我不会在这里使用尾递归累加器,而是使用
[Key|match(Element, T)]作为递归器。