简体   繁体   English

OCaml,多态函数

[英]OCaml, Polymorphic Functions

I do not have much experience with OCaml. 我对OCaml没有太多经验。 I need some help understanding Polymorphic functions. 我需要一些帮助来了解多态函数。

Code: 码:

# let hxyz = if x then y else z val h : bool -> 'a -> 'a -> 'a = <fun>

# let ixyz = if x then y else y val i : bool -> 'a -> 'b -> 'a = <fun>

Question: 题:

Can you explain to me why the second function has 'b as the second argument and not 'a like the first function? 您能向我解释为什么第二个函数具有'b作为第二个参数而不是'a类似于第一个函数吗?

It has to do with the types being inferred in your expressions. 它与表达式中推断出的类型有关。

                        same type since both branches of an `if` expression must be same type
                        ↓      ↓
let h x y z = if x then y else z
                 ↑  
                 must be `bool` since its in the place of a condition

So we end up with 所以我们最后得到

val h : bool -> 'a -> 'a -> 'a
        ↑        ↑     ↑     ↑
        x        y     z     return type
                same type

With the second expression, its similar only one of the variables isn't used, so its type can potentially be anything (isn't constrained to any rules in your expression definition). 对于第二个表达式,其相似之处仅是不使用其中一个变量,因此其类型可以是任意类型(不受表达式定义中任何规则的约束)。

          unused, could be any type
          |             are the same variable, therefore same type
          ↓             ↓      ↓
let i x y z = if x then y else y
                 ↑  
                 must be `bool` since its in the place of a condition

So we end up with 所以我们最后得到

val h : bool -> 'a -> 'b -> 'a
        ↑        ↑     ↑     ↑
        x        y     z     return type

Here, both 'a and 'b represents some arbitrary type that aren't necessarily the same. 在这里, 'a'b表示某种不一定相同的任意类型。 For example, 'a could be any type, but all 'a 's are the same type. 例如, 'a可以是任何类型,但是所有'a ”都是相同的类型。 Same goes for 'b . 'b

'a and 'b could be the same type, but they don't have to be. 'a'b 可以是同一类型,但不一定必须是。 z in your second expression is of type b' since it doesn't have any restrictions on what type it can be, therefore it doesn't have to be type 'a like it does in the first expression. 第二个表达式中的zb'类型b'因为它对可以成为哪种类型没有任何限制,因此它不必像第一个表达式中那样为'a类型。

Both branches of an if must return the same type. if的两个分支必须返回相同的类型。 Consider how if would look if it weren't inline: 考虑一下如果不是内联的话会如何看:

val if : bool -> 'a -> 'a -> 'a

Now in your first example both y and z are used in if so ocaml inferes they are the same type. 现在在您的第一个示例中,如果ocaml推断出它们是同一类型,则同时使用y和z。 In the second example though z is not used so nothing is infered about it. 在第二个示例中,虽然没有使用z,所以没有任何推断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM