Is there a way to call the constructor for an F# record type in F#?
My motivation is I've been using the applicative validation from FSharpx but find myself writing lots of boilerplate functions that just construct records.
The buildAddress function for instance in simply boilerplate and I would love to get rid of it if possible.
let buildAddress streetNumber streetLine1 streetLine2 suburb state postcode =
{
Address.StreetNumber = streetNumber
StreetLine1 = streetLine1
StreetLine2 = streetLine2
Suburb = suburb
State = state
Postcode = postcode
}
let validateAddress streetNumber streetLine1 streetLine2 suburb state postcode =
buildAddress
<!> isNumber streetNumber
<*> Success streetLine1
<*> Success streetLine2
<*> Success suburb
<*> Success state
<*> validatePostcode postcode
F# records are actually generated with a constructor, but it doesn't seem to be available from F# code. Probably the CompilationMapping attribute handles that, since there aren't any attributes on the constructor itself.
What you can do, is get to the constructor using standard .NET reflection (Activator.CreateInstance
) or the FSharp one (FSharpValue.MakeRecord
, FSharpValue.PreComputeRecordConstructor
will get you a function to use). All of them will want to get the arguments as an array of boxed objects however, so it won't mesh well with applicative validation.
I don't think you'll get a cleaner solution than what you have now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With