Skip to content

Instantly share code, notes, and snippets.

@isaacabraham
Created May 20, 2024 09:20
Show Gist options
  • Save isaacabraham/bf1f93e94c829eda08c4a197b2554117 to your computer and use it in GitHub Desktop.
Save isaacabraham/bf1f93e94c829eda08c4a197b2554117 to your computer and use it in GitHub Desktop.
// A generic Record
type Person<'T> = {
Name: string
Age: int
Singleton: 'T -> 'T list
}
// Creating a value with an "open" generic argument (?)
let personRec : Person<'T> = {
Name = "Isaac"
Age = 42
Singleton = fun (name: 'T) -> [ name ]
}
// These all work just fine, either executed one-by-one in FSI or all together. What's the generic type of personRec though?
personRec.Singleton "Prash"
personRec.Singleton 123
personRec.Singleton {| Name = "Prash" |}
// This does NOT work.
personRec
(*
error FS0030: Value restriction: The value 'it' has an inferred generic type
val it: Person<'_a>
However, values cannot have generic type variables like '_a in "let x: '_a". You can do one of the following:
- Define it as a simple data term like an integer literal, a string literal or a union case like "let x = 1"
- Add an explicit type annotation like "let x : int"
- Use the value as a non-generic type in later code for type inference like "do x"
or if you still want type-dependent results, you can define 'it' as a function instead by doing either:
- Add a unit parameter like "let x()"
- Write explicit type parameters like "let x<'a>".
This error is because a let binding without parameters defines a value, not a function. Values cannot be generic because reading a value is assumed to result in the same
everywhere but generic type parameters may invalidate this assumption by enabling type-dependent results.
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment