Case Title DU

How do I make this test pass by filling in 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"

      

+3


source to share


1 answer


In this case, the following actions will be performed:

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 join case has some arguments. For example:



type DU =
  | ACaseName
  | BThereCake of int

      

If you want to extract the name from <@ BThereCake @>

, not just from <@ BThereCake(12) @>

, you need to add another 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 @>

      

+10


source







All Articles