Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In F# how can I produce an expression with a type of Func<obj>?

Tags:

f#

c#-to-f#

I'm working with an api that requires a value of type Func. (Specifically, I'm trying to call ModelMetadataProviders.Current.GetMetadataForType().

How can I construct that value in F#?

like image 473
Christopher Bennage Avatar asked Jul 13 '10 14:07

Christopher Bennage


People also ask

What temp is C in F?

1 Celsius is equal to 33.8 Fahrenheit.

What is 1 C equal to in Fahrenheit?

Answer: 1° Celsius is equivalent to 33.8° Fahrenheit. Let us use the formulae of conversion between Celsius and Fahrenheit scales. Explanation: The formula to convert Celsius to Fahrenheit is given by °F = °C × (9/5) + 32.

What temperature in Fahrenheit is 50 C?

Answer: 50° Celsius is equal to 122° Fahrenheit.

How do you calculate F to C?

Fahrenheit to Celsius Exact Formula In other words, if you'd like to convert a temperature reading in Fahrenheit to Celsius: Start with the temperature in Fahrenheit (e.g., 100 degrees). Subtract 32 from this figure (e.g., 100 - 32 = 68). Divide your answer by 1.8 (e.g., 68 / 1.8 = 37.78)


1 Answers

When calling a method that takes any delegate of the Func you shouldn't need to explicitly create the delegate, because F# implicitly converts lambda expressions to delegate type (in member calls). I think that just calling the method with lambda function should work (if it doesn't, could you share the error message?)

Here is a simple example that demonstrates this:

type Foo() = 
  member x.Bar(a:System.Func<obj>) = a.Invoke()

let f = Foo()
let rnd = f.Bar(fun () -> new Random() :> obj)

In your case, I suppose something like this should work:

m.GetMetadataForType((fun () -> <expression> :> obj), modelType)

Note that you need explicit upcast (expr :> obj), to make sure the lambda function returns the right type (obj). If you want to assign the lambda function to a local value using let, then it won't work, because implicit conversion works only when it is passed as an argument directly. However, in that case, it makes the code a bit nicer.

like image 133
Tomas Petricek Avatar answered Sep 19 '22 08:09

Tomas Petricek