【发布时间】:2015-04-29 17:28:20
【问题描述】:
给定以下代码:
Prelude> let f x = if (x) then 55 else "foo"
为什么编译器会寻找Num [Char]?
<interactive>:2:23:
No instance for (Num [Char]) arising from the literal `55'
In the expression: 55
In the expression: if (x) then 55 else "foo"
In an equation for `f': f x = if (x) then 55 else "foo"
但是,在 Scala 中,它会找到55 和"foo" 的最小上限,即Any:
scala> def f(x: Boolean) = if (x) 55 else "foo"
f: (x: Boolean)Any
import scala.reflect.runtime.universe._
scala> lub( List[Type]( typeOf[Int], typeOf[String] ) )
res4: reflect.runtime.universe.Type = Any
Haskell 和 Scala 的类型推断之间的主要区别是什么?
【问题讨论】:
-
主要区别在于 Scala 有子类型,而 Haskell 没有。一个不太重要的区别可能是 Scala 中的数字不是多态的,尽管我还不足以肯定 Scala 的专家。
-
编译器查找
Num [Char],因为"foo"是一个字符串,即[Char],并且出现在55的另一个分支中。这意味着55也必须是[Char]类型,并且搜索了一种将数字55解释为字符串的方法(所述实例)。
标签: scala haskell type-inference