Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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.


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. 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?

like image 584
Petr Avatar asked Jun 08 '14 11:06

Petr


People also ask

What is recursion in Haskell?

Recursive functions play a central role in Haskell, and are used throughout computer science and mathematics generally. Recursion is basically a form of repetition, and we can understand it by making distinct what it means for a function to be recursive, as compared to how it behaves.

Does Haskell support recursion?

Recursion is important to Haskell because unlike imperative languages, you do computations in Haskell by declaring what something is instead of declaring how you get it. That's why there are no while loops or for loops in Haskell and instead we many times have to use recursion to declare what something is.


1 Answers

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?

Yes, exactly this happens. The Haskell 2010 report has a section on the topic.

like image 145
András Kovács Avatar answered Oct 11 '22 10:10

András Kovács