Is it possible to pass a F# function by Reflection?
(*in module A*)
type Foo() =
static member bar n = {1..n}
let functionUsingFoobar (x:(int -> #('a seq)) n =
let z = BarFoo.ofSeq (x n)
z.count
(* in module B
here is where I want to pass Foo.bar by reflection*)
let y = functionUsingFoobar Foo.bar 1000
I cannot invoke the member without the args parameter, so partial function application through InvokeMember cannot work.
let foo = new Foo()
let z = foo.GetType().InvokeMember("bar", System.Reflection.BindingFlags.InvokeMethod, null, foo, [|1000|])
(*tried null, [||], [|null|] for args parameter*)
I'm out of ideas how to pass the function by reflection
The problem is that GetMethod returns a MethodInfo, but you need an F# function value. The easiest way to overcome this mismatch is probably to use CreateDelegate to create a .NET delegate from the method, and then treat the Invoke method as a function value of the correct type:
let d =
typeof<Foo>.GetMethod("bar").CreateDelegate(typeof<System.Func<int,seq<int>>>)
:?> System.Func<int,seq<int>>
functionUsingFooBar d.Invoke 1000
If this is what I think you want, it works just fine
type Foo() =
static member bar n = {1..n}
let functionUsingFoobar (x:(int -> #('a seq))) n =
(x n) |> Seq.length
let y = functionUsingFoobar Foo.bar 1000
let foo = new Foo()
let z = fun t -> foo.GetType().InvokeMember("bar", System.Reflection.BindingFlags.InvokeMethod, null, foo, [|t|])
Related
I'm new to F# and functional programming and need some help. I come from c# so my mindset still gets in the way a bit.
I need to pass some options to a function and I'm using a record for this. One of the options is a continuation function unit -> Option<'a>. I can't figure out how to define the record type. Below is an example of what I've been trying.
type Func2<'a> = 'a -> 'a option
type ProcessOptions = {
func1: int -> int option
func2: Func2<int> // This works...
//func2: Func2<'a> // ... but this is what I'm trying to achieve - so that I can pass any Func2<'a> using this record.
}
let f1 a =
let r = Some a
printfn "f1: %A" r |> ignore
r
let f2 (a:'a) =
let r = Some a
printfn "f2: %A" r |> ignore
r
let f3 (processOptions:ProcessOptions) =
processOptions.func1(3) |> ignore
processOptions.func2 789 |> ignore
()
let f4 (processOptions:ProcessOptions) =
processOptions.func1(4) |> ignore
//processOptions.func2 "abc" |> ignore // as a result this does not work...
()
[<EntryPoint>]
let main argv =
f1(1) |> ignore
f2 123 |> ignore
f2 "abc" |> ignore
let fo = {
func1 = f1
func2 = f2
}
f3 fo
let fo1 = {
func1 = f1
func2 = f2
}
f4 fo1
0
A member inside a record cannot be a generic function (that you can call with different types of arguments such as int or string). It will always have one fixed type.
A trick you can use is to define a simple interface with a generic method:
type Func =
abstract Invoke<'a> : 'a -> 'a option
Now your members in the record can be just of type Func (with no generic type arguments), but the Invoke method inside Func will be generic:
type ProcessOptions =
{ func1: Func
func2: Func }
Creating Func values is a bit harder than writing ordinary functions, but you can use object expressions:
let f1 =
{ new Func2 with
member x.Invoke(a) =
let r = Some a
printfn "f1: %A" r |> ignore
r }
And you can now pass around ProcessOptions and call the Invoke method with different types of arguments:
let f4 (processOptions:ProcessOptions) =
processOptions.func1.Invoke 4 |> ignore
processOptions.func2.Invoke "abc" |> ignore
f4 { func1 = f1; func2 = f1 }
Here you need to make the record generic - with somehting like
type ProcessOptions<'a> = {
func1: int -> int option
func2: Func2<'a> // ... but this is what I'm trying to achieve - so that I can pass any Func2<'a> using this record.
}
I need a datatype that will be completely opaque in F# with equality defined in terms of JS ===. WebSharper manual says that I should override Equals but I can't make it work.
let x : OpaqueType = X<_>
let f (y : OpaqueType) =
if x = y then // this line should be translated to `if (x === y)`
42
else
10
So, what is the correct definition of OpaqueType?
Of course, I can use obj and add an inline function that will do x === y but I'd like to have something more awesome.
I would go for something like this:
module Test =
open IntelliFactory.WebSharper
[<JavaScript>]
let Counter = ref 0
[<Sealed>]
[<JavaScript>]
type T() =
let hash =
incr Counter
Counter.Value
[<JavaScript>]
override this.GetHashCode() =
hash
[<JavaScript>]
override this.Equals(other: obj) =
other ===. this
[<JavaScript>]
let Main () =
let a = T()
let b = T()
JavaScript.Log(a, b, a = b, a = a, hash a, hash b)
Equality and hashing are expected to be consistent by .NET libraries (for example, for use in Dictionary). They are also associated with types through virtual methods, so inlining will not work correctly. The above code gives you a type with reference-like equality semantics.
I need a type that will be translated into a plain JS object so that F# field access will be translated into simple JS field access (this is necessary, since the object will be sent through postMessage, so it'll lose all its methods).
Again, I need
let x = a.b
to be translated into
var x = a.b;
without any method calls.
Here is a slightly modified example from the F# Reference:
namespace T
open IntelliFactory.WebSharper
[<JavaScript>]
module A =
type MyClass =
val a : int
val b : int
new(a0, b0) = { a = a0; b = b0; }
let myClassObj = new MyClass(35, 22)
let x = myClassObj.b
This won't translate with
x: error : Failed to translate property access: b.'
Ok, let's make those vals mutable:
namespace T
open IntelliFactory.WebSharper
[<JavaScript>]
module A =
type MyClass =
val mutable a : int
val mutable b : int
new(a0, b0) = { a = a0; b = b0; }
let myClassObj = new MyClass(35, 22)
let x = myClassObj.b
This will be successfully translated, but… MyClass.New returns an empty object. The question now starts looking much like a bugreport, right? So, back to the question.
Are there any other ways to achieve what I want?
There are additional issues with record-style constructors "{x = y}". I will have to look into this again on F# 3.0, the older F# did not produce sensible quotations for those and we did some partial workarounds in WebSharper. Right now your example breaks. So here is the working code with a static method instead of a constructor:
type MyClass private () =
[<DefaultValue>]
val mutable a : int
[<DefaultValue>]
val mutable b : int
static member Create(a0, b0) =
let c = MyClass()
c.a <- a0
c.b <- b0
c
let test () =
let myClassObj = MyClass.Create(35, 22)
let x = myClassObj.a
let y = myClassObj.b
JavaScript.Log(x, y)
Trivially, a record would also work.
In some cases where you want to go really low-level you can annotate members with the Inline attribute. When this is too much overhead you can use untyped API:
let x = obj ()
x?a <- 1
let y = x?a
JavaScript.Log(x, y)
try this:
type MyClass (a, b) =
member val A = a with get
member val B = b with get
let myClassObj = new MyClass(35, 22)
let x = myClassObj.B
Given an F# record:
type R = { X : string ; Y : string }
and two objects:
let a = { X = null ; Y = "##" }
let b = { X = "##" ; Y = null }
and a predicate on strings:
let (!?) : string -> bool = String.IsNullOrWhiteSpace
and a function:
let (-?>) : string -> string -> string = fun x y -> if !? x then y else x
is there a way to use F# quotations to define:
let (><) : R -> R -> R
with behaviour:
let c = a >< b // = { X = a.X -?> b.X ; Y = a.Y -?> b.Y }
in a way that somehow lets (><) work for any arbitrary F# record type, not just for R.
Short: Can quotations be used to generate F# code for a definition of (><) on the fly given an arbitrary record type and a complement function (-?>) applicable to its fields?
If quotations cannot be used, what can?
You could use F# quotations to construct a function for every specific record and then compile it using the quotation compiler available in F# PowerPack. However, as mentioned in the comments, it is definitely easier to use F# reflection:
open Microsoft.FSharp.Reflection
let applyOnFields (recd1:'T) (recd2:'T) f =
let flds1 = FSharpValue.GetRecordFields(recd1)
let flds2 = FSharpValue.GetRecordFields(recd2)
let flds = Array.zip flds1 flds2 |> Array.map f
FSharpValue.MakeRecord(typeof<'T>, flds)
This function takes records, gets their fields dynamically and then applies f to the fields. You can use it to imiplement your operator like this (I'm using a function with a readable name instead):
type R = { X : string ; Y : string }
let a = { X = null ; Y = "##" }
let b = { X = "##" ; Y = null }
let selectNotNull (x:obj, y) =
if String.IsNullOrWhiteSpace (unbox x) then y else x
let c = applyOnFields a b selectNotNull
The solution using Reflection is quite easy to write, but it might be less efficient. It requires running .NET Reflection each time the function applyOnFields is called. You could use quotations to build an AST that represents the function that you could write by hand if you knew the record type. Something like:
let applyOnFields (a:R) (b:R) f = { X = f (a.X, b.X); Y = f (a.Y, b.Y) }
Generating the function using quotations is more difficult, so I won't post a complete sample, but the following example shows at least a part of it:
open Microsoft.FSharp.Quotations
// Get information about fields
let flds = FSharpType.GetRecordFields(typeof<R>) |> List.ofSeq
// Generate two variables to represent the arguments
let aVar = Var.Global("a", typeof<R>)
let bVar = Var.Global("b", typeof<R>)
// For all fields, we want to generate 'f (a.Field, b.Field)` expression
let args = flds |> List.map (fun fld ->
// Create tuple to be used as an argument of 'f'
let arg = Expr.NewTuple [ Expr.PropertyGet(Expr.Var(aVar), fld)
Expr.PropertyGet(Expr.Var(bVar), fld) ]
// Call the function 'f' (which needs to be passed as an input somehow)
Expr.App(???, args)
// Create an expression that builds new record
let body = Expr.NewRecord(typeof<R>, args)
Once you build the right quotation, you can compile it using F# PowerPack. See for example this snippet.
From the MSDN documentation I understand that if Run is implemented it will be called automatically at the end of the computational expression. It says that:
builder.Run(builder.Delay(fun () -> {| cexpr |}))
will be generated for the computational expression. Run and/or Delay will be omitted if they are not defined in the workflow builder. I was expecting my ReaderBuilder to return a list of MyItem objects when Run is called automatically. So I do not understand why I'm getting a type mismatch error. The errors are generated by the return statement inside the ProcedureBuilder foo at the end of my code listing here. Could someone please explain what I'm misunderstanding about workflow builders and what I have implemented incorrectly?
I'm getting the following errors:
The type ''a list' is not compatible with the type 'ReaderBuilder'
Type constraint mismatch. The type 'a list is not compatible with type ReaderBuilder The type ''a list' is not compatible with the type 'ReaderBuilder'
open System
open System.Data
open System.Data.Common
open System.Configuration
let config = ConfigurationManager.ConnectionStrings.Item("db")
let factory = DbProviderFactories.GetFactory(config.ProviderName)
type Direction =
| In
| Out
| Ref
| Return
type dbType =
| Int32
| String of int
type ReaderBuilder(cmd) =
let mutable items = []
member x.Foo = 2
member x.YieldFrom item =
items <- item::items
item
member x.Run item =
items
type ProcBuilder(procedureName:string) =
let name = procedureName
let mutable parameters = []
let mutable cmd:DbCommand = null
let mutable data = []
member x.Command with get() = cmd
member x.CreateCommand() =
factory.CreateCommand()
member x.AddParameter(p:string*dbType*Direction) =
parameters <- p::parameters
member x.Bind(v,f) =
f v
member x.Reader = ReaderBuilder(cmd)
member x.Return(rBuilder:ReaderBuilder) =
data
let (?<-) (builder:ProcBuilder) (prop:string) (value:'t) =
builder.Command.Parameters.[prop].Value <- value
type MyItem() =
let mutable _a = 0
let mutable _b = String.Empty
let mutable _c = DateTime.Now
member x.a
with get() = _a
and set n = _a <- n
member x.b
with get() = _b
and set n = _b <- n
member x.c
with get() = _c
and set n = _c <- n
let proc name = ProcBuilder(name)
let (%) (builder:ProcBuilder) (p:string*dbType*Direction) =
builder.AddParameter(p)
builder
let (?) (r:DbDataReader) (s:string) = r.GetOrdinal(s)
let foo x y =
let foo = proc "foo" % ("x", Int32, In) % ("y", String(15), In)
foo?x <- x
foo?y <- y
foo {
do! foo?x <- x
do! foo?y <- y
return foo.Reader {
let item = MyItem()
item.a <- r.GetInt32("a")
item.b <- r.GetString("b")
item.c <- r.GetDateTime("c")
yield! item
}
}
The problem in your example is that the foo.Reader { ... } block has a return type MyItem list (because this is what the Run member of the ReaderBuilder type returns). However, the Return member of ProcBuilder expects an argument of type ReaderBuilder.
The data field of ReaderBuilder will be always an empty list, so this is also suspicious. I think you probably want to change the Return of ProcBuilder to take an argument MyItem list instead.
However, I think that using custom computation builder for database access doesn't really give you much advantage. You're not creating a "non-standard computation" in some sense. Instead, you probably just want a nice syntax for calling commands & reading data. Using the dynamic operator can make this quite elegant even without computation builders - I wrote an article about this some time ago.