Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make this fully polymorphic in OCaml?

in OCaml

    let nth_diff_type i (x, y, z) =
        match i with
         1 -> x
        |2 -> y
        |3 -> z
        |_ -> raise (Invalid_argument "nth")

So the current type is int->('a,'a,'a)->'a, right?

It implies that x, y, z must have the same type.

So my question is that is it possible to give it maximum polymorphic, so that x, y, z don't need to have the same type?

like image 761
Jackson Tale Avatar asked Dec 21 '22 11:12

Jackson Tale


1 Answers

No, it isn't.

A function in OCaml should have only one return type. You can have different argument types if your return type is unique:

let nth_diff_type i (x, y, z) =
    match i with
    | 1 -> `Fst x
    | 2 -> `Snd y
    | 3 -> `Thd z
    |_ -> raise (Invalid_argument "nth")

// val nth_diff_type :
//   int -> 'a * 'b * 'c -> [> `Fst of 'a | `Snd of 'b | `Thd of 'c ] = <fun>

If you would like to create a few utility functions for triplets, unfortunately you have to define them separately:

let fst3 (x, _, _) = x
let snd3 (_, y, _) = y
let thd3 (_, _, z) = z
like image 109
pad Avatar answered Jan 13 '23 18:01

pad