Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array element matching bug on empty arrays #46

Closed
oguimbal opened this issue Sep 11, 2021 · 3 comments
Closed

Array element matching bug on empty arrays #46

oguimbal opened this issue Sep 11, 2021 · 3 comments
Labels
wontfix This will not be worked on

Comments

@oguimbal
Copy link
Contributor

oguimbal commented Sep 11, 2021

Hi !

Describe the bug

import { match, __, not } from 'ts-pattern';

console.log(match([]) // Logs 馃憠 first
  .with([__], () => 'first')
  .otherwise(() => 'default'));

console.log(match([]) // Logs 馃憠 first
  .with([not(__.nullish)], () => 'first')
  .otherwise(() => 'default'));

Even if the first is a bit ambiguous, I would at least expect the second one NOT to print "first"...

Code Sandbox with a minimal reproduction case

https://codesandbox.io/s/icy-glade-3ty9l?file=/src/index.ts

Versions

  • TypeScript version: 4.3.4
  • ts-pattern version: 3.2.5
  • environment: any
@gvergnaud
Copy link
Owner

I agree this behavior is confusing, but it's expected. [subpattern] patterns are list patterns, matching any list in which all elements match the subpattern, including empty lists. If you want to match empty lists separately a workaround is to add a .with([], handler) clause before your [__] pattern.

In retrospect, I don't think this was a great API choice because it can be confused with an unary tuple pattern (a pattern matching a list with a single element). I've been thinking about introducing a separate list(subpattern) helper that would look like this:

import { match, list, __ }from 'ts-pattern';

match(someList)
   .with([], () => 'empty list')
   .with([__], () => 'list with a single element')
   .with(list(not(null)), () => 'list with n elements')
   .exhaustive();

But this would be a breaking change, which makes it a bit tricky to release.

@oguimbal
Copy link
Contributor Author

It would be tricky indeed 馃

That said, it would be more intuitive, IMO.
And it would match Haskells behaviour.

Maybe for ts-pattern v4 馃コ ?

@gvergnaud gvergnaud added the wontfix This will not be worked on label Sep 23, 2021
@gvergnaud gvergnaud mentioned this issue Jan 9, 2022
@gvergnaud
Copy link
Owner

Closing since TS-Pattern v4 has been released and fixes this problem. Release note

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
wontfix This will not be worked on
Projects
None yet
Development

No branches or pull requests

2 participants