[ANN] ppx_viewpattern initial release

I’m glad to announce the initial release of ppx_viewpattern – transformation for view patterns in OCaml.

It attempts to imitate Haskell view patterns. I wrote this ppx rewriter mostly out of curiosity, rather than need, but it turned out neat enough that others might find it interesting or even useful.

Syntax

Use [%view? pat when exp] as a pattern to apply exp to whatever the pattern is matching and match the result of the exp application against pat.
This is analogous to the Haskell view pattern exp -> pat.

The above extension node payload syntax is the best I could come up with to combine an expression and a pattern. Honestly, I was even surprised that when exp is attached to a pattern in the AST (not a case), because normally it isn’t part of the pattern itself.

Example

This allows one to write

(* These cases are exactly like reduction rules! *)
let rec reduce = function
  | Add (Int n1, Int n2) -> Some (Int (n1 + n2))
  | Add ([%view? Some p1' when reduce], p2) -> Some (Add (p1', p2))
  | Add (p1, [%view? Some p2' when reduce]) -> Some (Add (p1, p2'))
  (* ... *)
  | _ -> None

instead of

(* These nested cases are so annoying! *)
let rec reduce = function
  | Add (Int n1, Int n2) -> Some (Int (n1 + n2))
  | Add (p1, p2) ->
    begin match reduce p1 with
      | Some p1' -> Some (Add (p1', p2))
      | None ->
        begin match reduce p2 with
          | Some p2' -> Some (Add (p1, p2'))
          | None -> None
        end
    end
  (* ... *)
  | _ -> None

See examples/ on GitHub for more.

9 Likes