According to the CTP Readme

<h5>"?" operator enables definition of

dynamic member lookup</h5>

The ? and ?<- operators now treat their right-hand argument as a parse-time

symbol, and pass this symbol to the operator definition as a string argument. This enables the definition of

dynamic lookup as a library implementation of the ? operator.

1
2
3
4
5
6
7
8
9
10
11
    open System.Reflection
        
        let (?) (x: 'a) (prop: string) : 'b =
            // A simplified '?' operator for dynamic property
            // lookup using reflection
            let pi = typeof<'a>.GetProperty(prop)
            pi.GetValue(x, [||]) :?> 'b


        let statically        = "hello".Length
        let dynamically : int = "hello"?Length
By on 5/22/2009 12:02 AM ()

Thanks for the info.

I'm quite surprised and intrigued since I got this to work:

1
2
3
4
5
6
let x = ("bob",fun (x:int) -> x+1)

let v :int = x?Item2 8

printfn "v: %A" v

This actually works. I'll be thinking of some of the other possibilities for using this.

The one issue I ran into is that I couldn't use a generic function within the tuple:

1
2
let x = ("bob",fun x -> x)

this would result in an InvalidCastException when attempting to perform the cast upon returning from the (?) operator. I need to add some kind of code to perform the conversion from the generic FastFunc into the one specified by the 'b type parameter.

Using Reflector on the compiled output was also enlightening as well seeing how the compiler interpreted the expression.

This operator could be modified I suppose to allow method invocation by returning a FastFunc of the appropriate type that wraps the requested method named by prop.

I'm going to look into that approach and post back here if it works.

Thanks again.

-Patrick

By on 5/22/2009 3:50 AM ()

The problem with the generic function within the let x expression is that the let is being compiled into a generic method that creates seperate instances for x depending on the type needed for the generic function inside.

If I provide a type specification for x then everything works fine:

1
2
let v : int = x>int>?Item2 8

but you have to explicitly set the type parameter, otherwise you get System.Object.

By on 5/22/2009 4:17 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper