Given
type Unit = {
Name : string
Abbreviation : string
Value : float
}
module Lets =
let meter = { Name = "meter"; Abbreviation = "m"; Value = 1.0 }
let millimeter = { Name = "millimeter"; Abbreviation = "mm"; Value = 1e-3 }
How can I create a function with this signature?
let units () : Units[] = ...
F# Modules are just static classes when compiled.
Using reflection you should be able to grab these values with something like this:
module Lets =
type Dummy = | Dummy
let meter = { Name = "meter"; Abbreviation = "m"; Value = 1.0 }
let millimeter = { Name = "millimeter"; Abbreviation = "mm"; Value = 1e-3 }
let t = typeof<Lets.Dummy>.DeclaringType
t.GetProperties() |> Array.map(fun p -> p.GetValue(null, null) :?> Unit)
It's tricky to get the type of the module, but that trick will do it for you.
EDIT:
Updated to cast directly to Unit
. The cast as shown is unsafe, and will throw if GetValue
does not return a Unit
type.
Additionally unit
is a type in F#, it might be clearer to use a different name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.