Is there a short built-in expression for unifying a single case of discrimination?

I am working on the basics of F #, and I'm still at a point where I'm not sure what is possible or what is available. I think there should be a better way to do this:

I am considering a general demo scenario for using this code to protect an additional type.

type CustomerId = CustomerId of int type OrderId = OrderId of int 

At some point, I have a save code that needs to deploy an integer:

 dbcmd.Execute(CID = ???, OID = ???) 

Option A: voluminous, but works

 dbcmd.Execute(CID = match CustomerId with (CustomerId cid) -> cid, OID = match OrderId with (OrderId oid) -> oid) 

Option B is obtained from the answer in Reconciling with a short template in combination with one case in F #

This requires 2 lines, and if there are 4 or 5 things to turn around, I really start to dislike the β€œdistance” between the left and right sides of the let statement - I will most likely end up printing something out of order

 let (CustomerId cid, OrderId oid) = (CustomerId, OrderId) dbcmd.Execute(CID = cid, OrderId = oid) 

Option C: This is probably what I would prefer if nothing is better. This is clear, but consumes more vertical space than I would have hoped.

 let (CustomerId cid) = CustomerId let (OrderId oid) = OrderId dbcmd.Execute(CID = cid, OrderId = oid) 

Option D: This is what I hope. This does not actually work, as this is the syntax for packaging, not for deployment, but you get the idea

 dbcmd.Execute(CID = (CustomerId id), OID = (OrderId id)) 

Is there a compressed syntax similar to option D?

+5
source share
2 answers

I usually use one of these options, choosing between them quite a lot of intuition. Mostly I prefer option 1, but it does not work if I need to make the constructor private.

Option 1: specify templates in parameter declarations

You can do this because functional parameters do not have to be just identifiers, they can also be templates.

 let f (CustomerId cid) (OrderId oid) = let cmd = ... cmd.Execute( cid, oid ) 

Option 2: Create Special Access Functions

 type CustomerId = CustomerId of int with static member toInt (CustomerId id) = id cmd.Execute( CustomerId.toInt cid, ... ) 

Option 2b: same but with member instance

 type CustomerId = CustomerId of int with member this.asInt = match this with (CustomerId id) -> id cmd.Execute( cid.asInt, ... ) 
+7
source

You can also use lambda without changing or extending the type definition:

 cid |> fun (CustomerId i) -> i 
+3
source

Source: https://habr.com/ru/post/1245195/


All Articles