Skip to content

Instantly share code, notes, and snippets.

@j14159
Created February 17, 2020 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j14159/54719811d2cfa12258e14d9f0a43e304 to your computer and use it in GitHub Desktop.
Save j14159/54719811d2cfa12258e14d9f0a43e304 to your computer and use it in GitHub Desktop.
Working out `assert_match` that I've been missing from Erlang.
open Ppxlib
exception No_match
let assert_match_ext =
Extension.declare
"ppx_assert_match.assert_match"
Extension.Context.Expression
Ast_pattern.(ppat __ __)
(fun ~loc ~path:_ patt guard ->
let open Ast_builder.Default in
let main_case = case ~lhs:patt ~guard ~rhs:(eunit ~loc) in
let fail_case = case
~lhs:(ppat_any ~loc)
~guard:(None)
~rhs:([%expr failwith "No match."])
in
pexp_function ~loc [ main_case; fail_case ]
)
let _ =
Driver.register_transformation ~extensions:[assert_match_ext] "ppx_assert_match"
open OUnit2
let test_exact _ =
[%assert_match? ("hello", 2)] ("hello", 2)
type test_rec = { x : int; y : float }
let test_records _ =
let rec_a = { x = 1; y = 2.5 } in
[%assert_match? { x = 1; _ }] rec_a;
[%assert_match? { x = 1; y } when y > 2.1] rec_a
let suite = "Simple early tests" >::: [ "Exact match" >:: test_exact
; "Record matches" >:: test_records
]
let _ = run_test_tt_main suite
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment