简体   繁体   中英

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

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. 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

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.

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#.

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 (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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