Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding function signature

I was reading a paper and one of the most fundamental parts of it is the following function, written in Haskell:

fixP :: Eq a => (Parser a -> Parser a) -> Parser a
fixP h x = fixS f 
           where f s = h p x 
                       where p y = if x == y then s
                                             else fixP h y

My Haskell is rusty. As I understand it fixP takes 1 argument which is a function Parser a -> Parser a, where a is constrained to have equality defined. However the pattern matches 2 arguments, h and x. What is x referring to?

Additional type signatures involved:

type Parser a = State -> Set (a,State)

type State = String

type Set a = [a]

fixS :: Eq a => (Set a -> Set a) -> Set a

After reading and understanding the answer and for anyone interested; here's the same function written in javascript:

function fixP(h) {
    return function(x) {
        var f = function(s) {
            var p = function(y) {
                if(x == y) {
                    return s;
                } else {
                    return fixP(h)(y);
                }
            };
            return h(p)(x);
        };
        return fixS(f);
    };
}
like image 500
thwd Avatar asked Mar 13 '26 09:03

thwd


1 Answers

Note that fixP h has type Parser a. Since Parser a is a synonym for State -> Set (a, State), we see that fixP h is in fact a function:

(fixP h) :: State -> Set (a, State)

We can therefore apply this function to some argument x of type State. That looks like (fixP h) x. Since function application is left associative , (fixP h) x is the same as fixP h x.

In words: To define what fixP is, we define what it does to arguments, i.e. we define what fixP h is. Since fixP h is itself a function, we need to define it. We define it by specifying what it does to arguments, i.e. we define what (fixP h) x is. Left associativity of function application means the latter can be written fixP h x.

As to the question "what's x?": Its type is State, so it smells like some sort of parser state, which according to the type synonyms you gave is a string. Exactly what that string's role is, though, is not clear just from the types :)

like image 125
gspr Avatar answered Mar 15 '26 08:03

gspr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!