为什么类型推断对于面向对象的语言来说是不切实际的? [英] Why is type inference impractical for object oriented languages?

查看:129
本文介绍了为什么类型推断对于面向对象的语言来说是不切实际的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究一种新编程语言的理念,理想情况下我希望语言将一些功能和程序(面向对象)概念混合在一起。



我真的对Haskell这样的语言着迷的事情是它是静态类型的,但是你不需要注释类型(魔术感谢Hindley-Milner!)。

我真的很喜欢这种语言,但是在阅读了这个主题之后,似乎大多数人都同意类型推断对于子类型/对象定向是不切实际/不可能的,然而我不明白这是为什么。我不知道F#,但我知道它使用Hindley-Milner并且是面向对象的。



我真的很喜欢这种解释,最好的例子是面向对象语言不可能进行类型推断的场景。

解决方案

当使用nominal typing(这是一个键入系统,其中两个成员具有相同名称和相同类型的类不可互换)时,方法会有很多种类型如下所示:

  let f(obj)= 
obj.x + obj.y

任何既有成员 x 和成员 y (支持 + 运算符)的类型将被限定为 obj 和类型推断算法将无法知道哪一个是你想要的。



在F#中,上面的代码需要一个类型注释。因此,F#具有面向对象和类型推断,但不是同时(除了本地类型推断( let myVar = expressionWhoseTypeIKNow )),它总是有效的。 p>

I'm currently researching ideas for a new programming language where ideally I would like the language to mix some functional and procedural (object oriented) concepts.

One of the things that I'm really fascinated about with languages like Haskell is that it's statically typed, but you do not have to annotate types (magic thanks to Hindley-Milner!).

I would really like this for my language, however after reading up on the subject it seems that most agree that type inference is impractical/impossible with subtyping/object orientation, however I have not understood why this is. I do not know F#, but I understand that it uses Hindley-Milner AND is object-oriented.

I would really like an explanation for this and preferably examples on scenarios where type inference is impossible for object oriented languages.

解决方案

When using nominal typing (that is a typing system where two classes whose members have the same name and the same types are not interchangeable), there would be many possible types for a method like the following:

let f(obj) =
    obj.x + obj.y

Any class that has both a member x and a member y (of types that support the + operator) would qualify as a possible type for obj and the type inference algorithm would have no way of knowing which one is the one you want.

In F# the above code would need a type annotation. So F# has object orientation and type inference, but not at the same time (with the exception of local type inference (let myVar = expressionWhoseTypeIKNow), which always works).

这篇关于为什么类型推断对于面向对象的语言来说是不切实际的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆