Skip to content

Unexpected type constraint mismatch error (FS0193) #16804

Closed

Description

@brianberns

Using type constraints, it should be possible to require a parameter to provide two distinct implementations of a generic interface.

To reproduce the problem, compile the following program:

[<Interface>] type IBase<'T> = abstract Value : 'T
[<Interface>] type IString = inherit IBase<string>
[<Interface>] type IInt = inherit IBase<int>

let test<'U when 'U :> IString and 'U :> IInt> (impl : 'U) =   // error FS0193: Type constraint mismatch
    let iStr : IString = impl
    let iInt : IInt = impl
    iStr.Value, IInt.Value

Expected behavior

Should compile successfully. Note that the corresponding C# program compiles, so this is not a limitation in .NET:

interface IBase<T> { abstract T Value { get; } }
interface IString : IBase<string> {}
interface IInt : IBase<int> {}

class Program()
{
    static (string, int) Test<U>(U impl)
        where U : IString, IInt
    {
        var iStr = (IString) impl;
        var iInt = (IInt) impl;
        return (iStr.Value, iInt.Value);
    }
}

Actual behavior

error FS0193: Type constraint mismatch. The type ''U' is not compatible with type 'IInt'

Known workarounds

None

Related information

  • .NET 8.0

Activity

  1. added this to the Backlog milestone on Mar 4, 2024
  2. vzarytovskii commented on Mar 4, 2024

    @vzarytovskii
    Member

    It is by design, given simplified code:

    [<Interface>] type IBase<'T> = abstract Value : 'T
    
    let test<'U when 'U :> IBase<string> and 'U :> IBase<int>> (impl : 'U) =
        let iStr : IBase<string> = impl
        let iInt : IBase<int> = impl
        iStr.Value, IInt.Value

    When type checker sees a constraint 'U :> IBase<string> and 'U :> IBase<int> for the same type variable, it unifies string and int. One of the reasons why multiple instantiations of generic interfaces was not supported in F#.

    It has a separate language suggestion: fsharp/fslang-suggestions#1036

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions