为什么 Scala 的类型推断不如 Haskell 强大? [英] Why is Scala's type inference not as powerful as Haskell's?

查看:22
本文介绍了为什么 Scala 的类型推断不如 Haskell 强大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell 的类型推断引擎比 Scala 强大得多.在 Haskell 中,我很少需要显式地编写类型,而在 Scala 中,类型只能在表达式中推断,而不能在方法定义中推断.

The type inference engine of Haskell is much more powerful than Scala's. In Haskell I rarely have to explicitly write the types whereas in Scala the types can only be inferred in expressions but not in method definitions.

例如,请参阅以下 Haskell 代码片段:

For example, see following Haskell code snippet:

size xs = loop xs 0
  where
    loop [] acc = acc
    loop (_ : xs) acc = loop xs (acc+1)

它返回一个列表的大小.Haskell 编译器可以识别使用了哪些类型以及函数定义是什么.等效的 Scala 代码:

It returns the size of a List. The Haskell compiler can recognize what types are used and what the function definition is. The equivalent Scala code:

def size[A]: List[A] => Int = xs => {
  def loop: (List[A], Int) => Int = {
    case (Nil, acc) => acc
    case (_ :: xs, acc) => loop(xs, acc+1)
  }
  loop(xs, 0)
}

或者使用方法定义:

def size[A](xs: List[A]) = {
  def loop(xs: List[A], acc: Int): Int = xs match {
    case Nil => acc
    case _ :: xs => loop(xs, acc+1)
  }
  loop(xs, 0)
}

我的问题是:为什么我不能像下面这样写?

My question is: Why can't I write them like the following?

def size = xs => {
  def loop = {
    case (Nil, acc) => acc
    case (_ :: xs, acc) => loop(xs, acc+1)
  }
  loop(xs, 0)
}

再次使用方法定义:

def size(xs) = {
  def loop(xs, acc) = xs match {
    case Nil => acc
    case _ :: xs => loop(xs, acc+1)
  }
  loop(xs, 0)
}

是因为还没有人实施吗?Scala 的类型系统是否没有这种情况所需的那么强大?还是有其他原因?

Is it because nobody has implemented it yet? Is the type system of Scala not as powerful as needed for this case? Or are there other reasons?

推荐答案

主要原因是 Scala 的类型系统允许子类型,Hindley-Milner 类型推断算法 不支持.

The main reason is that the type system of Scala allows sub-typing, which the Hindley-Milner type inference algorithm does not support.

Haskell 没有子类型,因此算法在那里运行得更好,尽管 GHC 支持的许多流行类型系统扩展会导致类型推断再次失败,迫使您为某些表达式提供显式类型签名.

Haskell does not have sub-typing, so the algorithm works much better there, although many popular type system extensions supported by GHC cause type inference to fail again, forcing you to provide explicit type signatures for some expressions.

归根结底,这是在类型系统的能力和可以完成的类型推断数量之间的权衡.Scala 和 Haskell 只是做了不同的权衡.

In the end, it's a trade-off between the power of the type system and the amount of type inference that can be done. Scala and Haskell have simply made different trade-offs.

这篇关于为什么 Scala 的类型推断不如 Haskell 强大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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