In OCaml, how can I get the value attached to a variant constructor?
- User
In OCaml, how can I get the value attached to a variant constructor?
Assistant
In OCaml, you can access the value attached to a variant constructor using pattern matching. Here's an example:
type shape = Circle of float | Rectangle of float * float;; let get_radius (shape: shape) = match shape with | Circle r -> r | Rectangle _ -> 0.0;;In this example, we define a custom type
shapethat has two variant constructors:CircleandRectangle. Theget_radiusfunction takes ashapeargument and uses pattern matching to extract the radius value from theCircleconstructor. If the input is aRectangle, it returns 0.0 as there is no radius in that case.You can apply this pattern to your own variant types and constructors to access the values attached to them.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.