functiontypessmlpolyml

PolyML Functions and Types


[...] a pair of functions tofun : int -> ('a -> 'a) and fromfun : ('a -> 'a) -> int such that (fromfun o tofun) n evaluates to n for every n : int.

Anyone able to explain to me what this is actually asking for? I'm looking for more of an explanation of that than an actual solution to this.


Solution

  • What this is asking for is:

    1) A higher-order function tofun which when given an integer returns a polymorphic function, one which has type 'a->'a, meaning that it can be applied to values of any type, returning a value of the same type. An example of such a function is:

    - fun id x = x;
    val id = fn : 'a -> 'a
    

    for example, id "cat" = "cat" and id () = (). The later value is of type unit, which is a type with only 1 value. Note that there is only 1 total function from unit to unit (namely, id or something equivalent). This underscores the difficulty with coming up with defining tofun: it returns a function of type 'a -> 'a, and other than the identity function it is hard to think of other functions. On the other hand -- such functions can fail to terminate or can raise an error and still have type 'a -> 'a.

    2) fromfun is supposed to take a function of type 'a ->'a and return an integer. So e.g. fromfun id might evaluate to 0 (or if you want to get tricky it might never terminate or it might raise an error)

    3) These are supposed to be inverses of each other so that, e.g. fromfun (tofun 5) needs to evaluate to 5.

    Intuitively, this should be impossible in a sufficiently pure functional language. If it is possible in SML, my guess is that it would be by using some of the impure features of SML (which allow for side effects) to violate referential transparency. Or, the trick might involve raising and handling errors (which is also an impure feature of SML). If you find an answer which works in SML it would be interesting to see if it could be translated to the annoyingly pure functional language Haskell. My guess is that it wouldn't translate.