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

could some explain and show how to implement the fromPredicate function? #590

Open
deleite opened this issue Jan 7, 2021 · 2 comments
Open

Comments

@deleite
Copy link

deleite commented Jan 7, 2021

Could some help me understand the fromPredicate example in the:
https://github.com/MostlyAdequate/mostly-adequate-guide/blob/master/ch12.md#effect-assortment

I get that the first one would keep the lefts and rights and the second won't but I would like to see it running so it is easier to get the idea.

Thanks

@deleite
Copy link
Author

deleite commented Jan 15, 2021

here is what I came up. Please feel free to correct or confirm if this is right :)

const fromPredicate = f => v => { const predicate = f(v); return predicate?Either.of(predicate):left(Error('false!')); }

@KtorZ
Copy link
Member

KtorZ commented Jan 18, 2021

@deleite this doesn't quite work, if you look at the type signature, the end result should be a Either e a. There's little we know about e but we can settle on an Error or String here. However, we know that a must be the same type of the a also provided in input for the predicate. So instead of Either.of(predicate), you should return Either.of(v).

You could write it the following way:

// fromPredicate :: (a -> Bool) -> a -> Either e a
const fromPredicate = curry((predicate, a) => predicate(a)
  ? new Right(a)
  : new Left("predicate failed"));

// --- example

const predicate = s => s.startsWith("a", s);

const fruitsA = new List([ "apple", "pear", "banana", "apricot", "orange" ]);
const fruitsB = new List([ "apple", "apricot" ]);

validate(predicate)(fruitsA);
// Left('predicate failed')

validate(predicate)(fruitsB);
// Right({$value: ['apple', 'apricot']})

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