F# argument checking

arguments, code-contracts, design-by-contract, f#, quotations

Solution

As @svick mentioned in the comments, this is currently not going to work very well, because `<@ bar @>` will actually be represented as `Value(null, typeof<string>)`. So, you can check whether the value is `null`, but you cannot currently get the name of the parameter.

The part that you can do looks like this:

open Microsoft.FSharp.Quotations

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

However, this is something that might improve in the next version :-) This F# feature request would require the ability to represent the name of variables in the quotation. So perhaps check with the next version of F#!

Problem

F# has some nice succint argument checking functions that can be used like this: ``` let foo (bar : string) : string = if bar = null then nullArg "bar" ... ``` I prefer a more prescriptive expression, however, a la Code Contracts: ``` let foo (bar : string) : string = Contract.Requires (bar <> null, "bar is null") ... ``` The code I dream about writing is this, however: ``` let nonNull (expr : Expr) : unit = // quotation magic let foo (bar : string) : string = nonNull <@ bar @> ... ``` The question is: can this be expressed in F#; or put another way, is there a working implementation for nonNull in F#? It doesn't look like it to me but perhaps someone here can verify it.

Original source

Related problems