F#中的记录列表?

时间:2011-09-28 15:49:17

标签: list f# functional-programming records

您如何使用F#中的记录列表?您如何将其作为函数中的参数传递?我想做这样的事情:

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; ]

我需要一种方法来告诉我的功能“汽车”是汽车记录清单。

1 个答案:

答案 0 :(得分:6)

您的代码运行正常。它也可以写成:

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

如果您曾担心推断出错误的签名,则可以添加类型注释。例如:

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