开发者

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 t开发者_如何转开发ell 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 = //...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜