z-pattern-matching / z Goto Github PK
View Code? Open in Web Editor NEWPattern Matching for Javascript
Home Page: https://z-pattern-matching.github.io/
License: Apache License 2.0
Pattern Matching for Javascript
Home Page: https://z-pattern-matching.github.io/
License: Apache License 2.0
Hello there,
There seems to be an issue in the package.json.
Currently, you have a fixed git checkout to js-function-reflector
but that requires the user to have git available.
While this is no problem for your all-day developer, this means you need git at install-time. So including z
into software that is used by the average software "user" will become difficult (of course, we can question how often the average user uses npm).
Also, this makes it hard to use z
in environments where you wish to have as few dependencies as possible, such as docker containers or strict production machines.
Another argument against having git references is that you might wish to have "the correct" version in your software. Meaning when I create a package today, I want it to behave the same tomorrow to ensure the working of my package.
I can actually not reproduce this but a colleague had this issue. I suppose you can enforce it by removing git from your system and try to install z.
What are your thoughts on this?
There's already something in active use called z
and it has a very similar logo
It's a mathematical constraint system for proving software, and a big chunk of it is about pattern matching
When golang
took the same name as the existing high quality language go
, the existing language disappeared forever, despite that it had several compilers and books
Please consider renaming your project. The Way of Z
deserves to live, and formal methods are already much too rare
Just tried the following on Node.js v9.8.0:
▶ node
> const { matches } = require('z')
undefined
> matches({ x: 3 })((x = String) => `${x} is a String`, (x = Object) => 'Object')
'[object Object] is a String'
> const _ = require('lodash')
undefined
> _.isString({x: 3})
false
z.js file has a // TODO: istanbul coverage error: 'else path not taken'
warning, need to fix this
Hello, I've been browsing through source code trying to understand how the thing works and got question considering following function:
const matches = (subjectToMatch) =>
function () {
const functions = Object.keys(arguments).map(key => arguments[key])
return resolveMatchFunctions(subjectToMatch, functions)
}
Could you explain why is it using Object.keys / arguments instead of using rest args?
const matches = (subjectToMatch) => (...functions) =>
resolveMatchFunctions(subjectToMatch, functions)
I cant find any test explaining this thing.
Good job!
Thank you for a very useful library. It's a bit late to bring this up I think, but I thought I'd open an issue anyway; it seems like the current order of arguments is not great for partial application. From the README
examples:
const compress = (numbers) => {
return matches(numbers)(
(x, y, xs) => x === y
? compress([x].concat(xs))
: [x].concat(compress([y].concat(xs))),
(x, xs) => x // stopping condition
)
}
but if it accepted the case matchers first, it could just be:
const compress = matches(
(x, y, xs) => x === y
? compress([x].concat(xs))
: [x].concat(compress([y].concat(xs))),
(x, xs) => x // stopping condition
)
It's not hard to define a flipped around version wherever I use it, but it'd be handy if the library just exported a different version of matches
that took arguments in that order.
'text'.matches(
(x = 'text') => 'a'
)
it isn't returning a
, is throwing can't match anything for: text
instead
My most common use case is matching on the presence of a key in an object and binding a variable to it de-structured style, I noticed this idea made it into the tc39 pattern matching proposal and was wondering if you had plans to implement anything similar in z
?
example from proposal:
match (obj) {
{ x }: /* match an object with x */,
{ x, ... y }: /* match an object with x, stuff any remaining properties in y */,
{ x: [] }: /* match an object with an x property that is an empty array */,
{ x: 0, y: 0 }: /* match an object with x and y properties of 0 */
}
I'd be glad to take a crack at it and send a PR if not 😀
Reamde says
matches([1])(
(a, b, tail) => 'Will not match here',
(a = 2, tail = []) => 'Will not match here',
(a = 1, tail) => 'Will match here, tail = []'
)
but
let a = Z.matches([1])(
(a = 1, tail) => {
return 'a = 1, b = []'
}
);
console.log("a");
console.log(a); // undefined
let b = Z.matches([1])(
(b, tail = []) => {
return 'a = 1, b = []'
}
);
console.log("b");
console.log(b); // a = 1, b = []
I see you're using js-function-reflector
but does that mean you need to use babel-preset-es2015-reflector
?
It would be better to use
var matches = require('z')
var myReverse = list => {
return matches(list, // first param for `matches` is an Array, String, etc.
() => [],
(head, tail) => myReverse(tail).concat(head)
)
}
myReverse([1, 2, 3, 4, 5]) //[5, 4, 3, 2, 1])
or
var matches = require('z')
var myReverse = list => {
return matches(list)( // `matches` returns a function to use patterns
() => [],
(head, tail) => myReverse(tail).concat(head)
)
}
myReverse([1, 2, 3, 4, 5]) //[5, 4, 3, 2, 1])
instead of
require('z')
var myReverse = list => {
return list.matches ( // uses prototype
() => [],
(head, tail) =>
)
}
myReverse([1, 2, 3, 4, 5]) //[5, 4, 3, 2, 1])
Strange but when I use some of the snippets with typescript, it always returns the result of the first param. For example
import {matches} from 'z';
const person = { name: 'Maria' }
matches(person)(
(x = { name: 'John' }) => console.log('John you are not welcome!'),
(x) => console.log(`Hey ${x.name}, you are welcome!`)
)
returns John you are not welcome
.
e.g:
#!/usr/bin/env node
const { matches } = require('z')
const FILTERS = {
CATEGORY: 'CATEGORY',
PRICE: 'PRICE',
COLOR: 'COLOR',
ONLY_NEW: 'ONLY_NEW',
ONLY_IN_DISCOUNT: 'ONLY_IN_DISCOUNT'
}
const _30DaysAgo = Date.now() - 1000 * 60 * 60 * 24 * 30
const convertOptionsToQuery = filterOptions => matches(filterOptions.by)(
(b = FILTERS.CATEGORY) => ({ category: filterOptions.value }),
(b = FILTERS.COLOR) => ({ colors: filterOptions.value }),
(b = FILTERS.PRICE) => ({ price: { $gte: filterOptions.value[0], $lte: filterOptions.value[1] } }),
(b = FILTERS.ONLY_NEW) => ({ createdAt: { $gte: new Date(_30DaysAgo) } }),
(b = FILTERS.ONLY_IN_DISCOUNT) => ({ isInDiscount: true }),
(b) => ({})
)
convertOptionsToQuery({ by: 'CATEGORY', value: 'shirts' })
// ReferenceError: FILTERS is not defined
Strangely enough, it only happens if the code is ran as a file, if it is ran in the REPL it works.
This error seems to be related to js-function-reflector
.
What is the browser support?
"native" nowadays means "a system app" -- mobile or desktop, i.e. "does not depend on a web-browser"
what you wanted to say is "vanilla" -- b/c it dosnt need babel, webpack or a WASM compiler
can I have z on npm?
Let's say we have this:
matches(x)(
async (x, xs) => {
const thing = await somethingElse()
...
},
(x) => {
},
)
Will this even...?
js-function-reflector
as npm package instead git linkHey there,
I'm trying to get a grip on this library and would love to use it with objects.
Currently, I'm trying to parse a version and based on the object's major/minor/patch, do different things:
'use strict';
const matches = require('z').matches;
const semver = require('semver-utils');
const manual = {
major: '1',
};
const parsed = semver.parse('1.0.0');
// Always default
matches(parsed).call(parsed,
(x = {major: '1'}) => console.log('m_one'),
(x = {major: '2'}) => console.log('m_two'),
(x = null) => console.log('default'),
(x) => console.dir(x)
)
// Always 1 but static :(
matches(manual).call(manual,
(x = {major: '1'}) => console.log('m_one'),
(x = {major: '2'}) => console.log('m_two'),
(x = null) => console.log('default'),
(x) => console.dir(x)
)
Following the sample from the documentation results that Marie is welcome - it works as expected and my implementation for manual
does, too. But that is basic stuff I don't need.
I'd like to patternmatch things dynamically. I'm not sure if it's possible of if I'm just using the library in the wrong manner.
I've read about the .call
approach in other issues but this doesn't seem to help.
Help is much appreciated!
Transformed code with Babel not work.
Probably is due this is not set: from js-function-reflector
doc:
var functionReflector = require('js-function-reflector');
// If you are using babel transpiler
functionReflector = reflector.compiler('babel-preset-es2015');
Have an option that checks if the matching is exhaustive, and if it isn't then have it immediately throw an error that the matching isn't exhaustive.
I mean pattern matching is cool when it's a core language feature, but...
const { matches } = require('z')
const zCompress = numbers => matches(numbers)(
(x, y, xs) => x === y
? zCompress([x].concat(xs))
: [x].concat(zCompress([y].concat(xs))),
(x, xs) => x // stopping condition
)
const jsCompress = numbers => numbers.filter((n, i) => n !== numbers[i - 1])
const input = [1, 1, 2, 3, 4, 4, 4]
const count = 100000
function time(fn) {
const start = Date.now()
for (let i = 0; i < count; i++) fn(input)
return Date.now() - start
}
const zTime = time(zCompress)
const jsTime = time(jsCompress)
console.log('z: ', zTime + ' ms')
console.log('js: ', jsTime + ' ms')
console.log(`z took ${zTime / jsTime} times longer`)
MacBook Pro Mid 2014, macOS 10.15.5. Node 12.16.2.
$ node index.js
z: 12560 ms
js: 23 ms
z took 546.0869565217391 times longer
When I type npm i --save-dev z
it returns OK but it doesn't download the core module properly. Just the info on the module.
Hello!
First of all, great library, thank you!
I just introduced z
(version 1.0.8) to a project and I cannot seem to get it to work with strings. I created a sandbox in which I recreated the issue I faced. It also includes two tests from the test suite that don't work as expected. I'm not familiar with the source code but anyways let me know if I can be of help fixing this issue.
Here is the sandbox: https://codesandbox.io/s/w6kql5km47
Thank you in advance for your time looking into this!
Nice lib! Docs say
(x) => {} matches an array with a single element eg.: [1], [[1, 2, 3]](array with a single array), matches single character eg.: 'x' or matches a single number eg.:1
(x, xs) => {} matches array with more than one element. First parameter is the first element (head), second is others (tail)
Couldn't we use rest params to be more precise? If (x) => {}
matches a single element I'd expect (x, y) => {}
to match exactly two elements (array.length === 2
). I'd use (x, ...xs) => {}
to match an array with more than one element (first element (head) and others (tail)).
I'm running into what may be a conceptual issue rather than an actual issue. Are multi-character match variables supported?
E.g.
let string = "test"; match(string)( (s) => { console.log(s); } )
Executes as expected logging
test
but
let string = "test"; match(string)( (str) => { console.log(str); } )
generates no output.
trying to find length of a list
const findLength = (list) => matches(list)(
(x = []) => 0,
(_, xs) => 1 + findLength(xs)
)
nor
const findLength = (list) => matches(list)(
(x = [], xs) => 0,
(_, xs) => 1 + findLength(xs)
)
works
Hey so I'm testing out the possibility of using z with the reducer in redux with the following code:
export const reducer = (state, action) =>
matches(action.type)(
(x = 'ADD') => ({...state, counter: state.counter+1}),
(x = 'REM') => ({...state, counter: state.counter-1}),
x => {console.log(`no state ${x}`); return state}
);
and then in then in my main app (a counter) I have the following:
const Counter = ({value, onIncrement, onDecrement}) =>
<div>
<button onClick={onIncrement}>
+
</button>
{value}
<button onClick={onDecrement}>
-
</button>
</div>
const App = ({state, dispatch}) =>{
console.log(state)
return (<div>
<Counter value={state.counter} onDecrement={() => dispatch({type: "REM"})} onIncrement={() => dispatch({type: "ADD"})}/>
</div>)
}
export default connect(state => ( {state: state} ))(App);
but when I click a button returns no state REM
, in the stack trace I saw that subjectToMatch = "REM"
.
I have code like:
types.js
const Types = Object.freeze({
A: 'a',
B: 'b',
});
module.exports = Object.freeze({
...Types,
Types: Object.values(Types),
});
index.js
const Types = require('./types');
const { matches } = require('z');
const match = matches('a')(
(x = Types.A) => 'matched A',
(x = Types.B) => 'matched B',
);
console.info(match);
and the expected behavior is to just work as the x
is assigned by constant, but it seems not so just throwing an TypeError which looks like:
TypeError: Cannot read property 'A' of undefined
at eval (eval at Parser.pushBuffer (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\argument_parser.js:96:22), <anonymous>:1:13)
at Parser.pushBuffer (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\argument_parser.js:96:22)
at Parser.parse (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\argument_parser.js:67:14)
at module.exports (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\header_parser.js:10:21)
at reflector (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\index.js:34:30)
at module.exports (C:\Users\suhun\Downloads\z-test\node_modules\z\src\getMatchDetails.js:4:29)
at resolveMatchFunctions (C:\Users\suhun\Downloads\z-test\node_modules\z\src\z.js:9:26)
at functions (C:\Users\suhun\Downloads\z-test\node_modules\z\src\z.js:44:3)
at Object.<anonymous> (C:\Users\suhun\Downloads\z-test\index.js:5:27)
at Module._compile (internal/modules/cjs/loader.js:654:30)
I believe this should be filed in the js-function-reflector but I do it here because z
has a dependency on it, which appears to be maintained by you.
Hello, I like to contribute with graphic designs, in opensource projects, so if you need something from me like a new logotype or something else just say it, Im here ready to help you.
Greetings!
Nuno Jesus
So, I'm about to start using this lib in a project, but I figured out that there is no type declaration file for the project or a @types/z
package
Using z in a Redux project, I was very surprised to find that matches
doesn't work with atomic consts:
const { matches } = require('z')
const FOO = 'foo'
matches(FOO)(
(x = FOO) => console.log('foo is foo!'),
(x) => console.log('foo is not foo???')
)
This code results in "foo is not foo???", which is (ahem) not really what I was expecting.
I haven't dug into the source code to see how z works its magic, but it seems like this would be a really common use case.
When I found z
I wanted to improve it, bringing pattern matching to javascript will be a breakthrough. First of all I wanted to understand how it was implemented and what is better than reimplement it from scratch. A few days later I abandoned the idea because in my opinion this library has no future. I report the problems I have encountered.
z
bases its logic on functions "reflection?". The trick of reflection is to convert the function to string, Function.toString()
and then extract the match patterns from there. You can make an acceptably fast parser to save performance problems but this is not the main problem.
When we convert the function to string to extract the default values what we are doing is "serialize" the function. The problem is when we "deserialize", for this we need to use eval that is slow and has serious security problems and the worst thing is that we can only deserialize the build-in types, forget about doing match of something like (x = MyType) => x
The other option is to create a transform plugin for Babel similar to sparkler (made with sweet.js) https://github.com/natefaubion/sparkler
But I think it's best for the bright minds of https://github.com/tc39/proposal-pattern-matching/blob/master/README.md#object-patterns to do so.
I for my part have a third option and wanted to share it here in case z
crew want to follow this path, before make a separate library. I share a piece of code to see how it might look. There are no reflections or parsers, only vanilla js and the sintax is different
function matcher(v) {
return function (...funcs) {
const firstCall = funcs.map(fn => fn())
for (let i = 0; i < firstCall.length; i++) {
const [fn, x] = firstCall[i];
// TODO: this the most simply matcher
// we need dedicate matchers for all javascript types
if (v === x) {
return fn(x)
}
}
}
}
function match(x, ...y) {
return function(fn) {
return [fn, x, ...y];
}
}
// New sintax
const a = matcher(5)(
(x) => match(x)(console.log),
(x = 3) => match(x)(console.log),
(x = 5) => match(x)(console.log)
)
What is your opinion/decision ?? @leonardiwagner @Koleok
Currently I'm investigating the ability of implementing the following:
match({ a: 1, b: 2 })(
({ a = 3, b = 4 }) => 'doesnt match',
({ a = 1, ...c }) => 'matches with c = { b: 2 }',
({ a, b }, { c, d }) => 'doesnt match',
)
Compare to previous version:
match({ a: 1, b: 2 })(
(x = { a = 3, b = 4 }) => 'doesnt match',
(x = { a = 1, ...c }) => 'matches with c = { c: 2 }',
(x = { a, b }, y = { c, d }) => 'doesnt match',
)
So the unneeded parameter x
is removed. I can't find any closed issue addressed this idea. What's your thoughts on this thing?
Relate to previous issues: #16 #22 #23
I start to research another way to implement pattern matching, I make some progress but I don´t have more time to continue.
Is really hard to do a rich pattern matching library and retain a user friendly API. IMO create a parallel library to current tc39/proposal-pattern-matching is not the way to go. But I think this unfinnish work
could be use like a ES5 pollyfil of future pattern-matching
Babel transform. It seem another developers are made some progress in this direction: https://github.com/Jamesernator/pattern-match
Any way here is the repos of the working implementation. They are two packages:
Right now the code is working but will need create more assertion functions for match Objects, Arrays, ...
I hadn´t write docs beyond code comments and working test examples, sorry.
I hope this could be useful ...
Thanks for this library, it's really nice.
If found an issue with an example on the web page.
If you run this code, nothing matches, it returns undefined:
matches([1])(
(a, b, tail) => 'Will not match here',
(a = 2, tail = []) => 'Will not match here',
(a = 1, tail) => 'Will match here, tail = []'
)
I would have expected the 3rd case to match.
Did the library change and the docs haven't been updated?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.