package ppx_deriving_variant_string

  1. Overview
  2. Docs
OCaml PPX deriver that generates converters between variants and strings

Install

Dune Dependency

Authors

Maintainers

Sources

ppx_deriving_variant_string-1.0.1.tbz
sha256=9d253d2c4c0f38e42e0a93405508011ae707ba4e708c9ddd0c88fbd3c7632f07
sha512=25bf3725bfab353f3b6f5d67ff55cc4186419bfd537b0824ad5bd26f456470995376fe7b4f3d9eabac2105a5878f168a9a31da1e33d5cb8ea3e2b3a43cdf97b7

Description

OCaml PPX deriver that generates converters between regular or polymorphic variants and strings. Supports both OCaml and Reason casing.

Tags

syntax org:ahrefs

Published: 16 May 2024

README

ppx_deriving_variant_string

OCaml PPX deriver that generates converters between regular or polymorphic variants and strings. Supports both OCaml and Reason casing.

Quick Start

Install: opam install ppx_deriving_variant_string.

In Reason syntax:

[@deriving (fromString, toString)]
type foo =
  | [@as "first"] First
  | Second;

let a = fooFromString("first"); /* Some(First) */
let b = fooFromString("Second"); /* Some(Second) */
let c = fooFromString("First"); /* None */
let d = fooToString(First); /* "first" */
let e = fooToString(Second); /* "Second" */

In OCaml syntax:

type foo =
  | First [@as "first"]
  | Second
[@@deriving of_string, to_string]

let a = foo_of_string "first" (* Some(First) *)
let b = foo_of_string "Second" (* Some(Second) *)
let c = foo_of_string "First" (* None *)
let d = foo_to_string First (* "first" *)
let e = foo_to_string Second (* "Second" *)

Name mangling

If the type where the PPX is applied is named t, the generated functions won't include any prefix and will be just toString, fromString (or to_string, of_string).

Why not ppx_deriving show?

The original ppx_deriving includes a plugin named show which has some overlap in functionality. However it was missing a few things:

  • it doesn't include functionality to convert from strings to variants

  • showshows a backtick for polymorphic variants

  • it does support as (it's called printer), which supports cases with variants with payloads, but it's a bit more heavyweight, as one has to pass a formatter instead of just a string, example

  • printer is only supported in polyvars for some reason, but not on regular variants, which was a feature we wanted to have

Why not Melange jsConverter?

We originally used Melange jsConverter, but we ran into limitations when making code compatible with universal libraries, that have to run both on the client and the server.

Dependencies (3)

  1. ppxlib >= "0.23.0"
  2. dune >= "3.8"
  3. ocaml

Dev Dependencies (1)

  1. ounit with-test

Used by

None

Conflicts

None

OCaml

Innovation. Community. Security.