When you want to declare many values with the same type in a signature, the signature becomes really verbose. Could it be possible to have some syntactic sugar to allow something like:
val red, green, blue, yellow, magenta, cyan : color
instead of
val red : color
val green : color
val blue : color
…
There is no way to do this in the language. You could do it with a PPX, if you really wanted it…
Cheers,
Nicolas
The main problem is that the compiler does not accept the syntax val x,y,z. Otherwise I could use the same trick as I use for pseudo-parallel assignment let x,y,z = 1,2,3.
type 'a pi3 = 'a * 'a * 'a
val x,y,z : int pi3
It’s necessary to have one pi_n type constructor for each value of n, but this can be made in my “personal_ocaml_library” which contains some utility stuff that I incorporate in all my projects …
Yes, as mentioned, that syntax is not supported. But you could an extension node translated by a PPX, eg
[%%val (x, y, z : t)]
Cheers,
Nicolas
I think something like your proposed syntax would be a useful addition to the language, but it’s sometimes difficult to get agreement about syntax changes.
There is a way to share a type ascription among bindings in a signature, like this:
include module type of struct [@@@ocaml.warning "-8"]
let [red; green; blue; yellow; magenta; cyan] : color list = []
end
but it’s likely to annoy your readers.
You can also give local abbreviations to types in signatures, in case making the declarations shorter makes them easier to read:
type t := color
val red : t
val green : t
val blue : t
val yellow : t
val magenta : t
val cyan : t
If I declare the color type as a sum, every function f (x:color) must have a large
match x with Red → … | Green → … inside (or at least call an auxilliary function to convert Red, Green to useful values) before processing.
On the other hand, the color type can contain itself this useful information, and be abstracted by a signature. So the function f (x:color) has the information directly accessible in the parameter x.
To make things concrete (sorry for the comments : the posting seems to remove asterisks)
module type MT = sig
type color
val red : color val green : color …
val color_to_hsl : color → int * int * int (* converts a color into its HSL triplet )
end
module M : MT = struct
type color = int ( encoding rgb value )
let red = 0xFF0000 let green = … let …
let color_to_hsl x = ( use the rgb value x and convert it to hsl *)
end