How can I build an arbitrary currency function in a provider like F #?

When I tried to get the type providers to generate more idiomatic code, I started looking for returned currency functions from the provider.

This small piece of code:

let lambdaTest () =
    let inner =
        <@ fun myInt ->
                fun int2 -> sprintf "A string! %d %d" myInt int2 @>
    let innerType = inner.GetType()
    ProvidedProperty(
        "lambda", 
        innerType.GenericTypeArguments.[0], 
        IsStatic = true, 
        GetterCode = fun _ -> inner.Raw)

It seems that I need to work to provide int -> int -> stringif I know the signature in advance; but ideally, I would like to dynamically build nested lambda functions, something like this:

let rec inline curry<'a> format (func: Quotations.Expr<'a>) : Quotations.Expr<'a> =
    match format with
    | FString f ->
        curry<string -> 'a> f <@ fun (s : str) -> %func @>
    | FInt f ->
        curry<int -> 'a> f <@ fun (i: int) -> %func @>
    | Other (_, f) ->
        curry<'a> f func
    | End ->
        func

Unfortunately, the above is not a valid F # code due to conflicting types of returned quotes.

Does anyone know if there is a way to do this?

+4
source share
1 answer

, ( ), , , Expr.

, , printf, . args, "s" , "n" . , , ['s'; 'n'], string -> (int -> string), :

open Microsoft.FSharp.Quotations

let rec buildFunc args printers = 
  match args with
  | 's'::args ->
      // Build a function `string -> (...)` where the `(...)` part is function
      // or value generated recursively based on the remaining `args`.
      let v = Var("v", typeof<string>)
      let printer = <@@ "Str: " + (%%(Expr.Var v)) + "\n" @@>
      // As we go, we accumulate a list of "printers" which are expressions of
      // type `string` that return the variables we are building, formatted...
      Expr.Lambda(v, buildFunc args (printer::printers))
  | 'n'::args ->
      // Pretty much the same, but we use `string<int>` to convert int to string
      let v = Var("v", typeof<int>)
      let printer = <@@ "Num: " + (string<int> (%%(Expr.Var v))) + "\n" @@>
      Expr.Lambda(v, buildFunc args (printer::printers))
  | [] ->      
      // Builds: String.Format [| f1; f2; f3 |] where 'f_i' are the formatters
      let arr = Expr.NewArray(typeof<string>, List.rev printers)
      let conc = typeof<string>.GetMethod("Concat", [|typeof<string[]>|])
      Expr.Call(conc, [arr])

, :

open Microsoft.FSharp.Linq.RuntimeHelpers.LeafExpressionConverter

// Generate 'int -> (string -> (int -> string))'
let fe = buildFunc (List.ofSeq "nsn") []
fe.Type.FullName // Shows the right type in a bit ugly way

// Evaluate the expression & cast to a function type
let f = (EvaluateQuotation(fe) :?> (int -> (string -> (int -> string)))) 
f 1 "a" 2 // Works!
+5
source

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


All Articles