List of Records in F#?
Asked Answered
G

1

6

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.

Gazzo answered 28/9, 2011 at 15:49 Comment(4)
Would the problem not be the car1 and car2 declarations not being of type Car - so it cannot automatically determine the type signature.Pulque
Your code works just fine. The inferred signature of getRedCars is Car list -> Car list. What errors are you seeing?Piscary
I guess it does work. Seems that VS thought it was an error at first, but latest compile it works. This also works (wonder if it helps the compiler?): (fun (x : Visit) -> x.Color = "red") carsGazzo
I tested it too and it does work fine, but I am surprised that the single ; at the end of the body of getRedCars is valid. Using verbose syntax I would except only ;; for a top-level declaration, or ` in ... ` for a local expression.Felike
P
8

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 = //...
Piscary answered 28/9, 2011 at 15:57 Comment(3)
Thank you, I did not know the type annotation for lists. Thanks so much.Gazzo
@StephenSwensen: That's good for him to know. Also, section 5.2 of the Component Design Guidelines (PDF) recommends using the prefix notation, with four exceptions: list, option, array, and ref.Piscary
(deleted and reposted this comment since had major error mixing up prefix and postfix) @Matthew: note that the postfix syntax used for parameterized types is inherited from ML, but you can also use the .NET prefix syntax: list<Car>.Felike

© 2022 - 2024 — McMap. All rights reserved.