Checking F # Arguments

F # has some good succint argument validation functions that can be used as follows:

let foo (bar : string) : string =
    if bar = null then
        nullArg "bar"
    ...

I prefer a more prescriptive expression, however, in code contracts:

let foo (bar : string) : string =
    Contract.Requires (bar <> null, "bar is null")
...

The code I'm dreaming of writing is, however:

let nonNull (expr : Expr) : unit =
    // quotation magic

let foo (bar : string) : string =
    nonNull <@ bar @>
    ...

The question arises: can this be expressed in F #; or in another way, is there a working implementation for nonNull in F #?

It doesn't sound like me, but maybe someone here can check it out.

+4
source share
1 answer

@svick, , <@ bar @> Value(null, typeof<string>). , , null, .

, , :

open Microsoft.FSharp.Quotations

let nonNull (expr : Expr) =
  match expr with 
  | Patterns.Value(null, _) -> failwith "it is null"
  | _ -> ()

, , :-) F # . , , F #!

+4

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


All Articles