简体   繁体   中英

OCaml, Polymorphic Functions

I do not have much experience with 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?

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. For example, 'a could be any type, but all 'a 's are the same type. Same goes for 'b .

'a and 'b could be the same type, but they don't have to be. 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.

Both branches of an if must return the same type. 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. In the second example though z is not used so nothing is infered about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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