匹配元组列表中的一项 [英] Match one item in List of tuples

查看:87
本文介绍了匹配元组列表中的一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式为(string, int)的元组列表.我正在尝试搜索列表并返回其字符串成分与参数匹配的元组,如:let find_tuple string_name tuples_list =

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 =

我该怎么做?我不能完全包住它.有没有办法使用像(string, _) ->...这样的匹配语法?

How can I do this? I can't quite wrap my head around it. Is there a way to use matching syntax like (string, _) ->...?

推荐答案

您可以按以下步骤实现

let rec find_tuple string_name tuples_list =
       match tuples_list with
            [] -> raise Not_found
            |(s, i)::tl -> if s = string_name then (s, i) 
                                  else find_tuple string_name tl

或者简单地

List.find (fun s -> fst s = string_name) tuples_list

这篇关于匹配元组列表中的一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆