简体   繁体   English

F#不同类型的遍历列表

[英]F# Traversing list of different types

I have five different types: 我有五种不同的类型:

type Name        = string
type PhoneNumber = int
type Sex         = string
type YearOfBirth = int
type Interests   = string list
type Client      = Name * PhoneNumber * Sex * YearOfBirth * Interests

Which represent clients. 代表客户。 Then let's say I have three of these clients: 然后,假设我有以下三个客户:

let client1 = "Jon", 37514986, "Male", 1980, ["Cars"; "Sexdolls"; "Airplanes"]
let client2 = "Jonna", 31852654, "Female", 1990, ["Makeup"; "Sewing"; "Netflix"]
let client3 = "Jenna", 33658912, "Female", 1970, ["Robe Swinging"; "Llamas"; "Music"]
let clients = [client1; client2; client3]

How would I go about searching through clients for a certain element? 我将如何在clients搜索某个元素? Say, I have a method where I want to get the names of the clients with the same sex as me? 说,我有一种方法想要获取与我性别相同的客户名称? I've written the below function for at least determining whether the input sex is the same but that doesn't cut it apparently. 我写了下面的函数,至少可以确定输入的性别是否相同,但是显然并不能减少输入的性别。

let rec sexCheck sex cs = 
match cs with
| [] -> []
| c::cs -> if sex = c then sex else sexCheck sex cs

sexCheck "Male" clients

Any hints? 有什么提示吗?

You can accumulate the results in another parameter, like this: 您可以将结果累加到另一个参数中,如下所示:

let sexCheck sex cs = 
    let rec loop acc (sex:string) cs = 
        match cs with
        | [] -> acc
        | ((_, _, s, _, _) as c)::cs -> loop (if sex = s then c::acc else acc) sex cs
    loop [] sex cs

As usual, I would like to remind you what's the easiest way, by using the provided functions in F#: 和往常一样,我想通过使用F#中提供的函数来提醒您最简单的方法:

clients |> List.filter (fun (_, _, c, _, _) -> c = "Male")

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

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