2

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?

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
  • It appears that this is not possible - see this previous SO discussion http://stackoverflow.com/questions/4173283/how-do-i-translate-this-c-sharp-code-with-generic-type-constraints-to-f – John Palmer Jun 17 '13 at 10:32
  • Unfortunately, this is not possible in F#... the previous question already answers this very well. – Tomas Petricek Jun 17 '13 at 10:32
  • This [question](http://stackoverflow.com/questions/4173283/how-do-i-translate-this-c-sharp-code-with-generic-type-constraints-to-f) and [this one](http://stackoverflow.com/questions/3857474/how-to-constrain-one-type-parameter-by-another) suggest that, surprisingly, this is not possible in F# (or at least it wasn't possible). – Leaf Garland Jun 17 '13 at 10:33
  • Thanks - surprising indeed, but liveable with. – Tim Robinson Jun 17 '13 at 11:03

0 Answers0