kantord / emuto

manipulate JSON files
https://kantord.github.io/emuto/
MIT License
223 stars 7 forks source link

Design pattern matching syntax + roadmap #160

Open kantord opened 5 years ago

kantord commented 5 years ago

The basic idea is to have a syntax similar to this:

(
  ["foo", $bar] -> $bar.value * 2,
  [$first, {"baz": $value}] -> [$value, $first],
  $value, $value >= 3.14 -> "Bigger than 3.14",
  otherwise -> error "Nonsense"
)
kantord commented 5 years ago

Def syntax to define functions with pattern matching:

def factorial: (
    0 -> 1,
    $ -> $ * (($ - 1) factorial)
)
kantord commented 5 years ago

Perhaps ; should be considered instead of ,

kantord commented 5 years ago

A possible idea might be to use "matcher functions" for pattern matching. These would be simply functions that return either null, or any other value. When they return null, they are considered not to be a match. When they don't return null, they are considered to match their value.

A basic matcher function called match should be implemented. This function should take a tuple, for example $.age : $.age >= 18. If the condition in the second element is true, match $.age : $.age >= 18 should return $.age, otherwise it should return null.

An even better implementation for this could be a custom datatype only used for pattern matching. This datatype could encode a value + whether it's a matching value or not, and could be created using matchSuccess or matchFailure.

This combined with creating new matchers by wrapping existing matchers in data structures, etc should be quite powerful.

It would be also nice to reuse operators + and | in some way to create combined matchers. That should enable using P.alt, P.seq etc.. from parsimmon to match patterns in strings. related to https://github.com/kantord/emuto/issues/347