Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 246
Matthew Avatar asked Sep 28 '11 15:09

Matthew


1 Answers

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 = //...
like image 54
Daniel Avatar answered Sep 22 '22 16:09

Daniel