Ocaml 模式匹配
我对 OCaml 和模式匹配还很陌生,所以我很难弄清楚这一点。
假设我有一个元组列表。我想要做的是根据元组中的第一个元素将参数与其中一个元组匹配,并且在这样做时,我想返回元组的第二个元素。例如,我想做这样的事情:
let list = [ "a", 1; "b", 2; "c", 3; "d", 4 ] ;;
let map_left_to_right e rules = match e with
| first -> second
| first -> second
| first -> second
如果我使用map_left_to_right“b”列表,我想得到2作为回报。 因此,我想列出规则列表中的所有第一个元素,并将参数与这些元素之一进行匹配,但我不知道该怎么做。我想我需要使用 List.iter 或 List.for_all 来做这样的事情。任何帮助将不胜感激。谢谢!
I am pretty new to OCaml and pattern matching, so I was having a hard time trying to figure this out.
Say that I have a list of tuples. What I want to do is match a parameter with one of the tuples based on the first element in the tuple, and upon doing so, I want to return the second element of the tuple. So for example, I want to do something like this:
let list = [ "a", 1; "b", 2; "c", 3; "d", 4 ] ;;
let map_left_to_right e rules = match e with
| first -> second
| first -> second
| first -> second
If I use map_left_to_right "b" list, I want to get 2 in return.
I therefore want to list out all first elements in the list of rules and match the parameter with one of these elements, but I am not sure how to do so. I was thinking that I need to use either List.iter or List.for_all to do something like this. Any help would be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模式匹配适用于您想要匹配固定模式列表的情况。在您当前的情况下,惯用的做法是
List.assoc
:当找不到元素时,您需要提供默认值。此处,
map_left_to_right "b" list 0
将按预期返回 2,而map_left_to_right "z" list 0
将返回 0。Pattern matching is intended for cases where you want to match a fixed list of patterns. In your current situation, the idiomatic thing to use is
List.assoc
:You need to provide a default when the element is not found. Here,
map_left_to_right "b" list 0
would return 2 as expected, andmap_left_to_right "z" list 0
would return 0.匹配仅匹配固定模式,而不匹配变量。在这种情况下,匹配的适当使用如下所示:(注意包含“默认”,就像在其他答案中一样)
如果我们想在没有找到任何内容的情况下返回 0,那么将这样调用:
All of这在功能上相当于另一个答案中的代码,实际上我建议使用该代码,因为它更小并且可以更好地利用现有库,但我认为我会给出这段代码,因为它更好地说明了模式匹配实际上是如何进行的应用于本例。
Match only matches against fixed patterns, not variables. An appropriate use of matching in this case would look like this: (note the inclusion of a "default" just as in the other answer)
If we want to return 0 if nothing is found, then this would be called like so:
All of this is functionally equivalent to the code in the other answer, and in practice I would recommend using that code since it's smaller and makes better use of existing libraries, but I thought that I would give this code because it better illustrates how pattern matching would actually be applied in this case.