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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch Alternative #48

Closed
rubgithub opened this issue Jun 17, 2020 · 1 comment
Closed

Switch Alternative #48

rubgithub opened this issue Jun 17, 2020 · 1 comment

Comments

@rubgithub
Copy link

I was looking for a functional alternative and I found mach

match(50)
  .on(x => x < 0, () => 0)
  .on(x => x >= 0 && x <= 1, () => 1)
  .otherwise(x => x * 10)
// => 500

Is there something similar in dartz?

https://codeburst.io/alternative-to-javascripts-switch-statement-with-a-functional-twist-3f572787ba1c

@spebbe
Copy link
Owner

spebbe commented Jun 18, 2020

hi!

hmm... i guess you could layer this on top of Either using these helpers:

extension Matching<L, R> on Either<L, R> {
  Either<L, R> on(bool predicate(R r), L value()) => flatMap((r) => predicate(r) ? left<L, R>(value()) : right<L, R>(r));
  L otherwise(L transformation(R r)) => fold(id, transformation);
}

Either<Result, A> match<A, Result>(A a) => right(a);

then you could could do:

  final result = match<num, num>(2)
    .on((x) => x < 0, () => 0)
    .on((x) => x >= 0 && x <= 1, () => 1)
    .otherwise((x) => x*10);

i'm not necessarily recommending this approach and i wouldn't claim that it's more "functional" than side effect free functions with normal conditionals/switches in them, but it's an interesting use case!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants