简体   繁体   English

在Haskell(GHC)中使用什么算法来导出递归表达式的类型?

[英]What algorithm is used in Haskell (GHC) for deriving types of recursive expressions?

Consider the following examples: 请考虑以下示例:

Non-recursive functions 非递归函数

 f x = x
 g y = f 'A'

GHC infers f :: a -> a GHC推断f :: a -> a

Mutually recursive functions 相互递归函数

 f x = const x g
 g y = f 'A'

Now GHC infers f :: Char -> Char , even though the type could be a -> a just in the previous case. 现在GHC推断f :: Char -> Char ,即使类型可能是a -> a只是在前一种情况下。

Polymorphic recursion 多态递归

 data FullTree a = Leaf | Bin a (FullTree (a, a))

 size :: FullTree a -> Int
 size Leaf = 0
 size (Bin _ t) = 1 + 2 * size t

Here GHC isn't able to infer the type of size , unless its explicit type is given. GHC无法推断出size的类型,除非给出其显式类型。


So it seems that Haskell (GHC) doesn't use polymorphic recursion (as described in Alan Mycroft: Polymorphic type schemes and recursive definitions ), because it can't infer polymorphic types in examples 2 and 3. But in the first case it correctly infers the most general type of f . 因此,看起来Haskell(GHC)不使用多态递归(如Alan Mycroft中描述的:多态类型方案和递归定义 ),因为它不能推断示例2和3中的多态类型。但在第一种情况下它正确推断最常见的f类型。 What is the exact procedure? 什么是确切的程序? Does GHC analyse the dependencies of expressions, groups them together (like f and g in the second example) and uses monomorphic recursion type inference on these groups? GHC是否分析表达式的依赖关系,将它们组合在一起(如第二个例子中的fg ),并对这些组使用单态递归类型推断?

Does GHC analyse the dependencies of expressions, groups them together (like f and g in the second example) and uses monomorphic recursion type inference on these groups? GHC是否分析表达式的依赖关系,将它们组合在一起(如第二个例子中的f和g),并对这些组使用单态递归类型推断?

Yes, exactly this happens. 是的,确实如此。 The Haskell 2010 report has a section on the topic. Haskell 2010报告有一个关于该主题的部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM