I'm trying to write a generic F# function with two type parameters, where one inherits from the other. (I'm writing code against Nancy, which uses some interesting generic contraints in the TinyIoC container code.)
I can write it in C# like this:
using System;
class Program {
static Func<T> Factory<T, U>(Lazy<U> lazy) where U : T {
return () => lazy.Value;
}
static void Main() {
var f = Factory<IComparable, string>(new Lazy<string>(() => "hello " + "world"));
Console.WriteLine(f());
}
}
I think this is the equivalent F#:
open System
let factory<'a, 'b when 'b :> 'a> (l : Lazy<'b>) : unit -> 'a =
fun () -> l.Value :> 'a
let f = factory<IComparable, _>(lazy "hello " + "world")
printfn "%s" (f ())
...but when I try this, I get an error against the 'factory' function:
error FS0698: Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution
Is it possible to write C#'s where U : T
constraint in F#? Am I doing it wrong?