Labeled argument & type annotation

For the combination of labeled argument and type annotation i have:

type sumtype = x:int->y:int->int
let sum:sumtype = fun ~x ~y -> x+y;;
print_int (sum ~y:2 ~x:3);;

Are there other ways or better ways ?

You can also write your example as

let sum ~(x:int) ~(y:int) = x + y;;

print_int (sum ~y:2 ~x:3);;


let sum : x:int -> y:int -> int = fun ~x ~y -> x + y

so you don’t need to find names for these types but still have the whole type signature. You can even leave out parts with _ for parts you want to have inferred (I often do that when I got long polymorphic variants in the result).

let sum : x:int -> y:_ -> int = fun ~x ~y -> x + y
1 Like

How about optional arguments with default values?

# let test ?(opt:int=4) x = opt + x;;
val test : ?opt:int -> int -> int = <fun>

And also:

# let test ?opt:(internal_name:int=4) x = opt + x;;
Error: Unbound value opt
# let test ?opt:(internal_name:int=4) x = internal_name + x;;
val test : ?opt:int -> int -> int = <fun>