简体   繁体   中英

List of Records in F#?

How do you work with a List of Records in F#? How would you even pass that as an argument in a function? I want to do something like this:

type Car = {
  Color : string;
  Make : string;
  }

let getRedCars cars =
  List.filter (fun x -> x.Color = "red") cars;

let car1 = { Color = "red"; Make = "Toyota"; }
let car2 = { Color = "black"; Make = "Ford"; }
let cars = [ car1; car2; ]

I need a way to tell my function that "cars" is a List of Car records.

Your code works just fine. It can also be written:

let getRedCars cars =
  List.filter (function {Color = "red"} -> true | _ -> false) cars

If you're ever concerned the wrong signature is being inferred, you can add type annotations. For example:

let getRedCars (cars:Car list) : Car list = //...

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