Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name of the DU case

Tags:

f#

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"
like image 406
Henrik Avatar asked Dec 04 '25 14:12

Henrik


1 Answers

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 @>
like image 190
Tomas Petricek Avatar answered Dec 06 '25 06:12

Tomas Petricek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!