Why is the type inferred for my ML function different than I expect?

后端 未结 1 452
盖世英雄少女心
盖世英雄少女心 2021-01-24 14:19

I made function that\'s name is maptree. And below is my code:

datatype \'a tree = LEAF of \'a | NODE of \'a tree * \'a tree;
fun maptree(f, NODE(X,         


        
1条回答
  •  孤独总比滥情好
    2021-01-24 14:46

    The Hindley-Milner type-inference algorithm allows you to get more general type than you expected.

    When the algorithm tries to infer the type for maptree, it assumes that f: 'a -> 'b (from the fact you're using f as a function). And nothing restricts the type of f further.

    If you, for example, defined the maptree function as follows (I used f twice in the LEAF case):

    fun maptree(f, NODE(X, Y)) = NODE(maptree(f, X), maptree(f, Y))
      | maptree(f, LEAF(X)) = LEAF(f (f X))
    

    Then the type-inference mechanism would have to restrict the type of f to 'a -> 'a (since we feed the output of the function to its input).

    The output of SML/NJ for the modified case:

    val maptree = fn : ('a -> 'a) * 'a tree -> 'a tree
    

    0 讨论(0)
提交回复
热议问题