I was trying to figure out what could be the syntax for a list with multiple types, and how could be the syntax for its pattern matching.
type [< int ; float ] list = [
~int: int ;
~float: float ;
]
let my_list = [ ~int:3 ; ~float: 4.6 ]
let () =
match my_list with
| ~int:d :: tl -> Printf.printf "%d\n" d
| ~float:g :: tl -> Printf.printf "%g\n" g
let f = (function lst ->
match lst with
... etc
)
let add_int lst d =
List.cons ~int lst
let add_float lst g =
List.cons ~float lst
I will ask a chat-bot to document me about how to achieve this kind of thing.
This looks like an alternate syntax for variants, which already give us a way to represent heterogeneous lists like this, in a way that is equivalent to what you have sketched here.
I am not sure what you have in mind with objects here, but I’m just observing that the code you posted is isomorphic to, and afaict, no more expressive than, code using polymorphic variants:
type 'a t = 'a list constraint 'a = [ `float of float | `int of int ]
let my_list = [ `int 3 ; `float 4.6 ]
let () =
match my_list with
| `int d :: tl -> Printf.printf "%d\n" d
| `float g :: tl -> Printf.printf "%g\n" g
let f = (function lst ->
match lst with
| `int i -> failwith "TODO"
| `float f -> failwith "TODO"
)
let add_int lst d =
List.cons (fun i -> `int i) lst
let add_float lst g =
List.cons (fun f -> `float f) lst