How do I make this test pass by filling out magic?
type DU =
| ACaseName
| BThereCake
let magic (q: Quotation<_>): string =
// smallest F# code in here?
open Expecto
let subject = magic <@ ACaseName @>
Expect.equal subject "ACaseName" "Should extract the NAME of the DU case"
In this case, the following will do:
open Microsoft.FSharp.Quotations
let magic (q: Expr<_>): string =
match q with
| Patterns.NewUnionCase(case, args) -> case.Name
| _ -> failwith "Not a union case"
let subject = magic <@ ACaseName @>
The question is, what do you want to do when the union case has some arguments. For example:
type DU =
| ACaseName
| BThereCake of int
If you wanted to extract the name from <@ BThereCake @> and not just from <@ BThereCake(12) @>, then you need to add one more case:
let magic (q: Expr<_>): string =
match q with
| DerivedPatterns.Lambdas(_, Patterns.NewUnionCase(case, args))
| Patterns.NewUnionCase(case, args) -> case.Name
| _ -> failwith "Not a union case"
let subject = magic <@ BThereCake @>
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