Search code examples
listf#functional-programmingrecords

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.


Solution

  • 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 = //...