F#搜索具有多个值/输入的记录

时间:2018-06-21 00:19:27

标签: f# pattern-matching records

对不起,如果这看起来像是一个愚蠢的问题,我仍在试图弄清楚F#的工作方式

因此,假设我建立了以下记录:

type person = 
{ fName: string;
  lName: string;
  age: int;
  weight: int; }

然后我创建一些人来填充记录

let joe   = {fName = "JOE";   lName = "QUAIL"; age = 34; weight = 133}
let jason = {fName = "JASON"; lName = "QUAIL"; age = 34; weight = 166}
let jerry = {fName = "JERRY"; lName = "PAIL";  age = 26; weight = 199}

所以我要做的是至少使用两个或三个参数(例如agelName),并且我想搜索person记录中所有满足输入的agelName的参数,目的是将它们添加到列表中。因此,在此示例中,我想在记录中搜索姓“ QUAIL”和34岁,这会让我得到Joe和Jason

在F#中,我认为模式匹配是必经之路,但我不知道如何实现模式匹配结构。

我的想法是使用这样的结构:

let myPeeps =
 List.filter (function
  | {age = ageImSearchingFor} & {lName = nameImSearchingFor} -> // add that person to a list or something
  | _ -> // do nothing
 )

但是我不知道该如何在F#中正确完成。

问题是,如何使用模式匹配(或其他方式)使用多个搜索参数搜索填充的记录?

1 个答案:

答案 0 :(得分:5)

您完全不需要模式匹配。 List.filter只需要返回一个布尔值,因此您可以执行以下操作:

List.filter (fun p -> p.age = 34 && p.lName = "QUAIL") myPeeps

这将返回

[joe; jason]

您可以定义一个函数,该函数接受一个人,并在满足该特定人的任何/所有条件时返回true,以根据您的特定需求自定义过滤器功能。