How can I get the compiler to insert the correct type in this example?

假装没事ソ 提交于 2019-12-12 22:33:54

问题


this is somehow follow-up on this question How can I get rid of this "Can not be generalised" error?

given the following types

type IModel<'value, 'target when 'target :> IModel<'value, 'target>> =
    abstract value: 'value with get

type IModelSimple<'value, 'target> =
    inherit IModel<'value, IModelSimple<'value, 'target>>
    abstract ReInitWith:  #IModel<_ , _ > -> 'target

and this function returning an object expression

let rec mkModelSimple<'value, 'target> vctor value =
    {
        new IModelSimple<'value, 'target> with
            member this.value = value
            member this.ReInitWith m = mkModelSimple vctor this.value
    }

I am getting this error

Type mismatch. Expecting a
    ''target'
but given a
    'IModelSimple<'value,'target>'

in the implementation of ReInitWith.


回答1:


As the compiler reports, you are defining a function where the inferred type contains itself and would be infinite. The way to fix this is to introduce some named type that breaks the recursion. One option is to define a new record with recursive type:

type IModel<'value, 'target when 'target :> IModel<'value, 'target>> =
    abstract value: 'value with get

type IModelSimple<'value, 'target> =
    inherit IModel<'value, IModelSimple<'value, 'target>>
    abstract ReInitWith :  #IModel<_, _> -> 'target

type Model<'value, 'target> =
  { Model : IModelSimple<'value, Model<'value, 'target>> }

let rec mkModelSimple<'value, 'target> vctor value =
    { Model = 
        { new IModelSimple<'value, Model<'value, 'target>> with
              member this.value = value
              member this.ReInitWith m = 
                mkModelSimple<_, _> vctor this.value } }

Just for the record, I think this code is pretty incomprehensible. It is definitely stretching what generics can sensibly do and I'd recommend avoiding doing things like this in production.



来源:https://stackoverflow.com/questions/48813678/how-can-i-get-the-compiler-to-insert-the-correct-type-in-this-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!