giogonzo / fp-ts-ramda

Ramda functions reimplemented in fp-ts
https://giogonzo.github.io/fp-ts-ramda/
MIT License
138 stars 9 forks source link

Question: allPass #21

Closed kightlingerh closed 4 years ago

kightlingerh commented 4 years ago

How do you want to go about allPass? I am by no means an expert in fp-ts, but I'm struggling to find a reasonable implementation which makes me tempted to go this route:

function _allPass <T>(funs: Array<Predicate<T>>, val: T): boolean { return funs.every(fun => fun(val)); }

giogonzo commented 4 years ago

Reading the docs at https://ramdajs.com/docs/#allPass

The function returned is a curried function whose arity matches that of the highest-arity predicate.

This will be hard/impossible to achieve, especially in a type safe way.

So, focusing on the simpler signature

allPass<A>(predicates: Array<Predicate<A>>, a: A): boolean

what you propose is of course correct, but as always, trying to showcase something from fp-ts itself, we could implement it as:

return pipe(
  predicates,
  Array.foldMap(monoidAll)(p => p(a))
);

monoidAll works with booleans and its concat returns true if both a and b are true foldMap folds and Array<A> into A using a monoid concat fn

Similarly, anyPass from ramda could be implemented using monoidAny. foldMap in this case wouldn't be optimized in terms of perf (scanning the entire array even if the first predicate already returns true), but I think it's ok anyway (and I'm not sure whether ramda itself does this optimization)

giogonzo commented 4 years ago

closed by #22