匹配元组列表中的一项
我有一个 (string, int)
形式的元组列表。我正在尝试搜索列表并返回其字符串组件与参数匹配的元组,如下所示: let find_tuple string_name tuples_list =
我该怎么做?我无法完全理解它。有没有办法使用像 (string, _) ->...
这样的匹配语法?
I have a List of tuples of the form (string, int)
. I'm trying to search through the list and return the tuple whose string component matches the parameter, as in: let find_tuple string_name tuples_list =
How can I do this? I can't quite wrap my head around it. Is there a way to use matching syntax like (string, _) ->...
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以按以下方式实现此目的
或简单地实现
You can achieve this as following
or simply
是的,您确实使用类似的匹配语法,但需要匹配防护(或者您可以使用 if then else)。
List
模块有一个名为find
的函数,它将返回与谓词匹配的第一个元素。它还具有函数filter
(和find_all
- 相同的函数),返回与谓词匹配的所有元素的列表。例如:编辑:更好的谓词:
但是更好的解决方案是使用
List.assoc
它适用于元组列表,并将元组视为键值对:虽然 < code>List.assoc 是元组的第二个元素(在您的情况下是
int
)。如果您想要元组的值,请重新创建它,或使用第一种方法。Yes, you do use matching syntax like that, but will need match guards (or you can use if then else). The
List
module has a function calledfind
that will return the first element that matches a predicate. It also has the functionfilter
(andfind_all
- same function) that returns a list of all the elements that match the predicate. For example:EDIT: a better predicate:
However the better solution is to use
List.assoc
which works on lists of tuples, and considers the tuples to be key-value pairs:Although the return value of
List.assoc
is the second element of the tuple (anint
in your case). If you want the value of the tuple, either recreate it, or use the first approach.