Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# record constructor function

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
like image 515
Brownie Avatar asked Aug 24 '14 09:08

Brownie


1 Answers

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.

like image 137
scrwtp Avatar answered Oct 19 '22 03:10

scrwtp