简体   繁体   English

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

[英]F# Search through records with multiple values/inputs

Sorry if this seems like a stupid question, I'm still trying to figure out how F# does things 对不起,如果这似乎是一个愚蠢的问题,我仍然在试图弄清楚F#是如何做的

So, say I established a record with the following: 所以,说我建立了以下记录:

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

and then I create some people to populate the record 然后我创建一些人来填充记录

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}

So what I want to do is take at least two or three parameters (say age , and lName ) and I want to search through the person record for all the people who satisfy the inputted parameters of age and lName with the goal being to add them to a list. 所以我想要做的是至少拿两三个参数(比如agelName ),我想在所有满足输入agelName参数的人的person记录中搜索,目标是添加它们到列表。 So in this example, I want to search through the record for last name "QUAIL" and age 34 and that would get me Joe and Jason 所以在这个例子中,我想通过记录搜索姓氏“QUAIL”和34岁,这将得到我和乔和杰森

In F#, I figure that pattern matching is the way to go, but I don't know how I would go about implementing that pattern match structure. 在F#中,我认为模式匹配是可行的方法,但我不知道如何实现模式匹配结构。

My idea was to use a structure like this: 我的想法是使用这样的结构:

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

But I don't know how that would be properly done in F#. 但我不知道如何在F#中做得恰到好处。

So the question is, how do I use pattern matching (or something else) to search through a populated record using multiple search parameters? 所以问题是,如何使用模式匹配(或其他东西)使用多个搜索参数搜索填充的记录?

You shouldn't need pattern matching at all for this. 你根本不需要模式匹配。 List.filter just needs that you return a bool, so you could do something like this: List.filter只需要你返回一个bool,所以你可以这样做:

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

This will return 这将返回

[joe; jason]

You can define a function that takes a person and returns true when any/all of your conditions are met for that particular person to customize the filter function for your particular needs. 您可以定义一个接受人的函数,并在满足特定人员的任何/所有条件时返回true,以根据您的特定需求自定义过滤器函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM