[discuss] multi-typed lists with labels

[discuss] multi-typed lists with labels

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.

Variants are not an alternative for objects, even if some people say we can do object oriented programming with .c.

I was trying to figure out how a better alternative for object oriented programming could look like.

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
1 Like

What is the difference with :

type 'a list = [ `float of float | `int of int ]

?

That defines a new type alias (shadowing the stdlib’s list) which is not actually any sort of list.

he probably meant

type 'a t = [ `float of float | `int of int ] list;;
 [ `float 1.; `int 2 ];;
- : [> `float of float | `int of int ] list = [`float 1.; `int 2]

Could you be confusing polymorphic variant type syntax with list syntax? They both use square brackets but they are quite different.

The advantage would be some kind of syntaxic sugar:

List.add ~f:5.6 my_list ;;
List.add ~d:8 my_list ;;

in stead of:

List.add (`f 5.6) my_list ;;
List.add (`d 8) my_list ;;

It would avoid the round brackets.

The syntax for pushing a new element could also be:

  ~f:5.8 :: my_list
  ~d:23 :: my_list