The value restriction

前端 未结 3 1382
醉梦人生
醉梦人生 2020-11-28 14:36

In OCaml you can\'t generalize a partially-applied curried function (the \"value restriction\").

What is the purpose of the value restriction? What unpleasant would

3条回答
  •  一向
    一向 (楼主)
    2020-11-28 14:48

    There is a nice description of weakly polymorphism here(side-effects-and-weak-polymorphism).

    Basically, let's take a look at the function below (caching the first ever value it sees):

    # let remember =
        let cache = ref None in
        (fun x ->
           match !cache with
           | Some y -> y
           | None -> cache := Some x; x)
      ;;
    val remember : '_a -> '_a = 
    

    As it involves imperative, value restriction is applied.


    However, let's assume there was no value restriction.

    Then its type becomes val remember : 'a -> 'a = .


    If I now do let () = remember 1, 1 is recorded inside cache, right?

    If I call for 2nd time, let x = 3 + remember 2, this should work, because 3 is integer, remember returns the same type as its argument. I am giving 2 here, so remember returns integer too (but value is 1 as we already remembered once). This should pass the type check.


    What if I call for 3rd time as let y = 3.0 + remember 2.0? Will it work again?

    According to remember's type and the reason behind my 2nd call, it also should work, because I am giving float to remember, and it should return float.

    But because the first time it already stored 1 (integer) inside, it will return 1 which is an integer. So the type check will fail, right?


    We can see that without value restriction or weakly polymorphism, due to the mutability is allowed, the whole type check will have trouble. In the silly case above, you need constantly manually check or keep track of what's the initial type remember stored.

提交回复
热议问题