Saturday 15 September 2012

haskell - Inferred type appears to detect an infinite loop, but what's really happening? -


In Andrew Koinig, the author uses the implementation of ML as a learning exercise and has a & ldquo; Incorrect & rdquo; Type assessment

For my surprise, the compiler has a type of

  'a list - & gt; In other words, this sort function accepts any type of list and returns a list of integers.  

It is impossible that the output input should be sorted; How could this possibly be of a different type? The reader will definitely familiarize his first impulse: I wonder if I have uncovered a bug in the compiler!

After thinking about something else about it, I realized that there is another way in which the function can ignore the argument: Probably sometimes it did not return at all. Indeed, when I do it Tried it, then it happened exactly: sort (blue) returned zero , but sorting any blank list would be in an infinite re-key loop

When translated into Haskell

  split [] = ([], []) partition Split (x: y: xs) = (x: s1, y: s2) where (s1, s2) = partition xs merge xs [] = xs merge [] ys = [x] Ys merge xx @ (x: xs) yy @ (y: ys) | X & lt; Y = x: merge xs yy | Otherwise = y: merge xx ys merge [] = [] Merge xs = merge (mergeresport p) where (p, q) = partition xs  

GHC is of the same type Guess:

  * Main & gt; : Merger of T Merge: (Ard A) => [T] - & gt; [A]  

How does this type of estimate?

This is actually a remarkable example; An infinite loop is being detected, essentially, compiled time ! In this example there is nothing special about Hindley-Milner's conclusion; It normally does the same.

Note that ghc gets the split and merge correctly:

  * main & Gt; : T split split :: [A] - & gt; ([A], [A]) * Men & gt; : T Merge Merge :: (Ord T) = & gt; [T] - & gt; [T] - & gt; [T]  

Now when it comes to mergeresort , it is normally a function, 1 → t 2 for some type 1 and 2 . Then it looks at the first row:

  Mergeresort [] = []  

and discover that 1 and < Sub>> 2 list type, T 1 = and 2 = [t 4 ]. Therefore, mergeart should be a function [t 3 ] → [t 4 ]. Next line

  Mergers Xs = Merge (Merge), where (P, Q) = partition xs  

it states that: / P >

This is the reason why you:

  * Maine & gt; : Merger of T Merge: (Ard A) => [T] - & gt; [A]  

In the context of logical conclusions is equal to the algorithm described above, but the specific sequence of the steps of the algorithm is as follows, for example, given on the Wikipedia page.)


No comments:

Post a Comment