0

I have:

- fun F p q = p q;
val F = fn : ('a -> 'b) -> 'a -> 'b

I know how to use it, for example by first having fun square x = x*x and then invoking F Sq 3. However, I don't quite understand the function expression in the second line. Can someone help paraphrase it in English and indicating which parameter is 'a and which is 'b'.

Old Geezer
  • 14,854
  • 31
  • 111
  • 198

1 Answers1

0

F here is a so called higher-order function which has two arguments:

  • p which has type 'a -> 'b (so it's a function!)
  • q which has type 'a
  • F (if applied first to an 'a -> 'b and then to an 'a produces an `b

The second line just tells you exactly this.

Moreover you know what is does: it plugs in q into p! (it applys p to q)

Your example of course is:

  • square: int -> int (so 'a and 'b here need both to be int as you use square in place of q)
  • 3 which has type int so the expression F square 3 is wellformed

It evaluates as:

F square 3
{ def F }
= square 3
{ def square }
= 3*3
{ arithmetic }
= 9
Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • I am still a bit confused. Where does it say ('a->'b)->`'a`->'b? Why not ('a->'b)->`'c`->'b? That is, why does `F p` result in the same type as the input type of `p`? – Old Geezer Oct 05 '15 at 01:36
  • Because of the body: `p q` - as you apply ´p` to `q` the domain of `p` needs to have the same type as `q` or this would not work - to the same reason the result must be the co-domain of `p` (why do you accept the `'b` there?) – Random Dev Oct 05 '15 at 04:21
  • 1
    Since `->` is right-associative, the type `('a -> 'b) -> 'a -> 'b` can be read with the extra set of parentheses as `('a -> 'b) -> ('a -> 'b)`. That is, F can be seen as a function that takes a function and returns it (F is the identity function for functions of one argument). – sshine Oct 05 '15 at 08:46