PolyML Functions and Types

北战南征 提交于 2019-12-10 20:08:16

问题


[...] 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.


回答1:


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.




回答2:


You can devise the following property:

fun prop_inverse f g n = (f o g) n = n

And with definitions for tofun and fromfun,

fun tofun n = ...
fun fromfun f = ...

You can test that they uphold the property:

val prop_test_1 =
    List.all
      (fn i => prop_inverse fromfun tofun i handle _ => false)
      [0, ~1, 1, valOf Int.maxInt, valOf Int.minInt]

And as John suggests, those functions must be impure. I'd also go with exceptions.



来源:https://stackoverflow.com/questions/40793384/polyml-functions-and-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!