While studying for a Functional Programming exam, I came across the following questions from a previous test:
t2 = (\x -> \y -> \z -> (x y, x (x z)))
t3 = t2 (take 3 . reverse) mnr mnr
For t2, it is asked to determine the most general type of the statement. The answer appears to be:
(a -> a) -> a -> a -> (a,a)
I am able to find the answer by entering the statement into WinHugs, but how is this answer found? I understand from my previous post that it has something to do with lambda functions though other than that I am at a loss to explain what is going on here.
The second part of the question (t3) then applies two functions to two instances of the variable mnr. For mnr = [0,1,2,3,4,5,6] this results in:
([6,5,4],[4,5,6])
How does this work? The functions take and reverse are clear but how are they applied to the lambda functions in t2?
Let’s start from the middle, at the result.
because
xis being applied to things (y,z, andx z), we know it has the type(a -> ?)where the question mark represents an unknown type. Now, the result ofxis being passed toxinx (x z), so its input type must be its output type:Now,
xis applied toyand toz, so they both must be of typea.x yandx (x z)are also both of typea(as that isx‘s return type), sot2returns something of type(a, a).Putting this together with the type of its arguments (
x,y, andz), we get that is has typeFor you second question, let’s first look at what things are bound to what variables in
t2‘s definition. The first argument is x, so in this caseThe next argument is y, so
Similarly for z,
The result will be
(x y, x (x z)), so let’s evaluate thiswith this specific case of
mnr = [0,1,2,3,4,5,6], we get