Type inference for default function / method arguments?

Witold Baryluk witold.baryluk at gmail.com
Tue May 11 12:56:42 UTC 2021


Also OCaml supports inference for default arguments, but 
considering very powerful type inference solver in Ocaml, that is 
kind of cheating too. 
https://caml.inria.fr/pub/docs/u3-ocaml/ocaml051.html  Example:

```ocaml
let substring ?pos:(p=0) ~length:l s = String.sub s p l;;
```

Here, `p` is inferred to be `int`:

```ocaml
val substring : ?pos:int -> length:int -> string -> string = <fun>
```

It inferred to be a for two reasons: default value (`0`) is an 
`int`, and `String.sub` second argument is supposed to be an 
`int`. However, it works even if the `p` is not used, and only 
the default value is used for initialization:

```ocaml
let f ?x:(x=42) = x;;
Warning 16: this optional argument cannot be erased.
val f : ?x:int -> int = <fun>
```

`x` is inferred to be an `int`.

This is different that, without default argument:

```ocaml
# let f ?x:x = x;;
Warning 16: this optional argument cannot be erased.
val f : ?x:'a -> 'a option = <fun>
```

Where `f` is a generic function, working with any type.

or

```ocaml
let rec list_map f ?(accum = []) l = match l with
     | head :: tail -> list_map f ~accum:(f head :: accum) tail
     | [] -> List.rev accum;;
val list_map : ('a -> 'b) -> ?accum:'b list -> 'a list -> 'b list 
= <fun>
```

accum is inferred to be a `list`.

I think it is pretty handy, and brings D a bit closer to more 
compact format, know from places like Ocaml, Haskell, or dynamic 
languages like Python.



More information about the Digitalmars-d mailing list