I'm trying to figure out why this doesn't compile.
type A() =
member __.M(f:DateTime -> seq<int>) = ()
member __.M(f:DateTime -> obj) = ()
let a = A()
a.M(fun d -> seq [d.Year]) // 'd' is indeterminate type
If I remove the second overload or add a type annotation to d, it does. Is it because some aspect of overload resolution occurs prior to type checking?
Yes, basically overloads make type inference hard. In this case, it seems like you're hoping that the compiler will do some sort of generalization of the types DateTime -> seq<int> and DateTime -> obj to get DateTime -> ? and then proceed from there, but I don't think it ever does that kind of "anti-unification".
Related
I'm trying to learn the TypeShape lib and playing with the IShapeMember per the snippet in the readme
type IShapeMember<'DeclaringType, 'Field> =
abstract Get : 'DeclaringType -> 'Field
abstract Set : 'DeclaringType -> 'Field -> 'DeclaringType
Here is my code in an effort to generalise a 'setter' function
let setMemberValue (value: 'b) (target: 'c) (shp: IShapeMember<'c>) =
shp.Accept { new IMemberVisitor<'c,'c> with
member x.Visit (m: ShapeMember<'c,'b>) = m.Set target value}
But this gives me the compile error: This code is not sufficiently generic. The type variable 'a could not be generalized because it would escape its scope.
(btw, that's not a type on the error, it indeed complains about variable 'a....)
I have tried all manner of Type wrangling but cannot get my head around what I'm doing wrong.
I'm not a TypeShape expert, but I think the problem here is that you're not honoring the signature of the Visit function, which is:
type IMemberVisitor<'TRecord, 'R> =
abstract Visit<'Field> : ShapeMember<'TRecord, 'Field> -> 'R
Note that the 'Field type parameter is determined by whoever calls Visit, not by you. Thus, your attempt to use the external value in the call to Set isn't sufficiently generic. Instead, you need a way to obtain an instance of 'Field from within the Visit function, so it works with whatever 'Field type the caller desires. This is easier said than done, but if you want a trivial example to start with, this will compile at least:
let visitor target =
{
new IMemberVisitor<'TRecord, 'R> with
member x.Visit (m: ShapeMember<'TRecord,'Field>) =
let value = Unchecked.defaultof<'Field>
let target' = m.Set target value
Unchecked.defaultof<'R>
}
There's also an example of calling Set from within Visit here, but it is more complex. I don’t think there is any way of doing it that is both simple and useful.
let setMemberValue (value: 'b) (target: 'c) (shp: IShapeMember<'c>) =
shp.Accept { new IMemberVisitor<'c,'c> with
member x.Visit (m: ShapeMember<'c,'d>) =
if typeof<'b> = typeof<'a> then //or convert 'b -> 'd function
m.Set target (box value :?> 'd)
else
failwith "The supplied type does not match the type of the target field"
}
Boxing and casting the supplied value to the type 'd did the trick. All wrapped in some form of type check in case the caller supplied value does not match that of the field being set
This code snippet reproduces a problem I am having with some production code. The function containsProperty represents a real world function that is actually in a library, so that I have no say in what the signature is.
The problem is that I can't figure out how to create a wrapper function that can take a normal function as argument, and then pass that on to containsProperty. I can call containsProperty directly with a function as a lambda expression, but I can't call it with a function that comes from some other source.
The function addToGroup is the best I've come up with so far, and it uses quotations. There are two problems with that approach, which I am trying to figure out. First, how do I get rid of the Func cast in the quotation? Perhaps somehow move it into addToGroup? Second, can I build on this in order to just pass a function? I haven't succeeded in finding something that doesn't produce either a compile time error or a runtime error.
The function addToGroup2 is what I'd like to do, but it doesn't compile. The error message is "No constructors are available for the type 'Quotations.Expr<'a>'".
Why do I bother to struggle with this? Because as long as I can't treat the passed in function as a first class value, I can't create the design I'm after. I want these functions to come along from a collection of records.
If you paste this snippet into LINQPad or something, comment out addToGroup2 and the calls to it, in order to make the snippet compile and run.
open System
open System.ComponentModel
open System.ComponentModel.DataAnnotations // Reference to this assembly required.
type CfgSettings = {
mutable ConnectionString: string
mutable Port: int
}
and CfgSettingsMetadata() =
static member containsProperty<'TProperty>(propertyExpression: Linq.Expressions.Expression<Func<CfgSettings,'TProperty>>) =
Console.WriteLine "good!"
static member addToGroup f =
CfgSettingsMetadata.containsProperty(FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.QuotationToLambdaExpression f) |> ignore
static member addToGroup2 (f: CfgSettings -> 'TProperty) =
CfgSettingsMetadata.containsProperty(FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.QuotationToLambdaExpression (Quotations.Expr<Func<CfgSettings,'TProperty>>f)) |> ignore
static member BuildMetadata () =
CfgSettingsMetadata.containsProperty(fun x -> x.ConnectionString)
CfgSettingsMetadata.containsProperty(fun x -> x.Port)
CfgSettingsMetadata.addToGroup <# Func<_,_>(fun x -> x.ConnectionString) #>
CfgSettingsMetadata.addToGroup <# Func<_,_>(fun x -> x.Port) #>
CfgSettingsMetadata.addToGroup2 (fun x -> x.ConnectionString)
CfgSettingsMetadata.addToGroup2 (fun x -> x.Port)
CfgSettingsMetadata.BuildMetadata()
Both answers in question Expression<Func<T, bool>> from a F# func helped me somewhat, but I haven't found a solution yet.
So, there are two questions here.
How to pass a function without having to wrap it in <# ... #>?
For this, you just need to add the [<ReflectedDefinition>] attribute to your method's parameter. It implicitly wraps the argument passed to it in a quotation.
type CfgSettingsMetadata() =
static member addToGroup([<ReflectedDefinition>] f: Expr<CfgSettings -> 'TProperty>) =
CfgSettingsMetadata.containsProperty(LeafExpressionConverter.QuotationToLambdaExpression f) |> ignore
// Example use:
CfgSettingsMetadata.addToGroup(Func<_, _>(fun x -> x.ConnectionString))
How to convert from Expr<a -> b> to Expression<Func<a, b>>?
This is indeed explained in the question you linked, although the API has changed a bit since then.
type CfgSettingsMetadata() =
static member addToGroup ([<ReflectedDefinition>] (f: Expr<CfgSettings -> 'TProperty>)) =
let call = LeafExpressionConverter.QuotationToExpression f :?> MethodCallExpression
let lambda = call.Arguments.[0] :?> LambdaExpression
let e = Expression.Lambda<Func<CfgSettings, 'TProperty>>(lambda.Body, lambda.Parameters)
CfgSettingsMetadata.containsProperty(e) |> ignore
// Example use:
CfgSettingsMetadata.addToGroup(fun x -> x.ConnectionString)
I'm trying to understand the variance rules for function types. It seems they don't treat input and output the same (up to duality). Consider this program.
let mk1 s = s |> Seq.iter (fun _ -> ())
// val mk1 : s:seq<'a> -> unit
let mk2 = mk1 : list<int> -> unit // Ok.
let mk3 () = [1]
// val mk3 : unit -> int list
let mk4 = mk3 : unit -> seq<int> // Type mismatch.
This is the error:
Type mismatch. Expecting a
unit -> seq<int>
but given a
unit -> int list
The type 'seq<int>' does not match the type 'int list'
It's my understanding that seq<int> is an interface type, one which int list implements, so I was expecting this cast to go through(*).
Two questions:
Why doesn't it?
Why is the cast producing mk2 ok?
(*) For theorists: I was expecting the elaborator to exhibit dual behaviour on the input and output positions of the function space type constructor. Is that wrong?
You have this:
let mk4 = mk3 : unit -> seq<int>
Which will not compile, the up-cast will happen automatically in the input parameter but never in the output of the function. This is in the spec, section 14.4.2 Implicit Insertion of Flexibility for Uses of Functions and Members.
This means that F# functions whose inferred type includes an unsealed type in argument position may be passed subtypes when called, without the need for explicit upcasts.
This makes possible to define another version of the function which is restricted to a subtype, which are the other cases you're showing.
Interestingly, you can use flexible types to define mk4 as follows:
let mk4 = mk3 : unit -> #seq<int>
It compiles but automatically lifts the type of mk4 up to unit -> int list
I get the value restriction error on let makeElem in the following code:
let elemCreator (doc: XmlDocument) =
fun name (value: obj) ->
let elem = doc.CreateElement(name)
match value with
| :? seq<#XmlNode> as childs ->
childs |> Seq.iter (fun c -> elem.AppendChild(c) |> ignore)
elem
| _ -> elem.Value <- value.ToString(); elem
let doc = new XmlDocument()
let makeElem = elemCreator doc
Why I get the value restriction error if anonymous function returned from elemCreator hasn't any generic parameters?
The compiler states that the infered type of makeElem is (string -> 'a -> XmlNode). But why it infers second parameter as 'a if I've declared it as obj?
I believe that this may be the "expected" behavior (although unfortunate in this case), as a result of the compiler's generalization and condensation processes. Consider Tomas's example:
let foo (s:string) (a:obj) = a
If you were to define
let bar a = foo "test" a
then the compiler will infer the type bar : 'a -> obj because it generalizes the type of the first argument. In your case, you have the equivalent of
let bar = foo "test"
so bar is a value rather than a syntactic function. The compiler does essentially the same inference procedure, except now the value restriction applies. This is unfortunate in your case, since it means that you have to explicitly annotate makeElem with a type annotation (or make it a syntactic function).
This looks like an unexpected behavior to me. It can be demonstrated using a simpler function:
let foo (s:string) (a:obj) = a
let bar = foo "bar" // Value restriction
One possible explanation might be that the F# compiler allows you to call a function taking parameter of some type with an argument of any subtype. So, you can call foo "hi" (new A()) without explicitly casting A to obj (which used to be required some time ago).
This implicit casting could mean that the compiler actually interprets bar as something like this:
let bar a = foo "bar" (a :> obj)
...and so it thinks that the argument is generic. Anyway, this is just a speculation, so you could try sending this as a bug report to fsbugs at microsoft dot com.
(The following is based solely on observation.)
If you have a function obj -> 'a, calls to that function are not used to infer/solve the type of its argument. An illustration:
let writeLine (arg: obj) = System.Console.WriteLine(arg)
writeLine is obj -> unit
let square x =
writeLine x
x * x
In the above function x is inferred as int because of (*). If a type could be constrained by obj then this function would not work (x would be inferred as obj prior to the use of (*), which would cause an error along the lines of: type obj does not support operator (*)).
I think this behavior is a Good Thing. There's no need to restrict a type as obj because every type is already implicitly convertible to obj. This allows your program to be more generic and provides better interoperability with the .NET BCL.
In short, obj has no bearing on type inference (yay!).
I need to cast a function with the signature Thing -> Thing -> int to a Comparison<Thing>.
For example, when I have:
Array.Sort(values, mySort)
I get an error stating "This expression was expected to have type Comparison but here has type Thing -> Thing -> int"
When I try this:
Array.Sort(values, (fun (a, b) -> mySort a b))
(actually, this is by way of a wrapper object)
I get an error stating "Type constraint mismatch. The type ''a -> 'b' is not compatible with the type 'Comparison'"
How am I supposed to provide a Comparison<T>?
FYI: Comparison<T> is a delegate with the signature 'T * 'T -> int
This works for me:
let values = [|1;2;3|]
let mySort a b = 0
Array.Sort(values, mySort)
But have you tried:
Array.Sort(values, Comparison(mySort))
Oddly, despite the fact that delegate signatures are expressed in tupled form (e.g. 'T * 'T -> int), you need to provide your function in curried form (e.g. fun a b -> mySort a b). See section 6.4.2 of the spec.