Type Inference in OCaml

时间:2016-02-03 04:21:50

标签: types functional-programming ocaml ml

I'm trying to wrap my head around OCaml's type inference notation.

For example:

# let f x = x [];; 
val f : ('a list -> 'b) -> 'b = <fun>

makes sense to me. The val f takes in a function x that takes in a list of 'a type and returns something of 'b type. Then f returns a 'b type as well since it just calls x.

However, once we get more arguments I get more confused.

# let g a b c = a b c;;
val g : ('a -> 'b -> 'c) -> 'a -> 'b -> 'c = <fun>

Can I assume that if the function has arguments, then the first parameters of the type inference will always be the arguments? And if I call a b c, is the order ((a b) c) or (a (b c))?

# let rec h m n ls = match ls with
  | [] -> n
  | x::t -> h m (m n x) t;;
val h : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a = <fun>

As for this one I'm confused as to how ('a -> 'b -> 'a) -> 'a was derived. I can see that 'b list corresponds to the ls variable and the last 'a corresponds to the type of the terminal symbol n.

1 个答案:

答案 0 :(得分:4)

  

我可以假设如果函数有参数,那么类型推断的第一个参数将始终是参数吗?

是的,函数类型的第一个参数是它的第一个参数的类型。

  

如果我打电话给b c,是订单((a b)c)还是(a(b c))?

订单是((a b) c)(你可以用这种更简单的方式思考)

  

至于这个我很困惑('a - &gt;'b - &gt;'a) - &gt; 'a得出了。我可以看到'b list对应于ls变量,而last'对应于终端符号n的类型。

你是对的。 ls类型为'b listn类型为'a

让我们考虑一下m的类型:

  1. 您知道n的类型为'a,因此您也可以派生(m n x)   类型为'a
  2. 您知道ls的类型为'b list,因此您可以派生x   输入'b
  3. m接受'a类型的两个参数并输入'b,并生成类型'a的结果。因此,m的类型为'a -> 'b -> 'a
  4. 因此,整个函数的类型为('a -> 'b -> 'a) -> 'a -> 'b list -> 'a