fp-ts
fp-ts copied to clipboard
[Question] Difference between `match` and `fold`
Prompted by a comment on fp-ts
Discord I searched the issues for an answer but haven't found an answer.
Why's there both match
and fold
for most data types even though they all seem to have the same signatures?
edit: that's not true for some data types like TaskEither, I'd be interested in understanding the underlying difference in theory between the two, if there is one.
match
is renamed fold
, which is deprecated right now.
@steida then something's off here, look at match
and fold
for TaskEither<E, A>
they are indeed different.
export declare const fold: <E, A, B>(
onLeft: (e: E) => T.Task<B>,
onRight: (a: A) => T.Task<B>
) => (ma: TaskEither<E, A>) => T.Task<B>
export declare const match: <E, B, A>(onLeft: (e: E) => B, onRight: (a: A) => B) => (ma: TaskEither<E, A>) => Task<B>
fold
seems to be more similar to chain
in that regard, where match
seems to be more similar to map
.
@enricopolanski You are right. Almost everywhere fold
is an alias of match
except for TaskEither
where fold
is an alias of matchE
.
https://gcanti.github.io/fp-ts/guides/code-conventions.html#what-an-e-suffix-means-eg-matche
I just spend a few minutes trying to figure out how to write this code:
// "A good example is when you are processing a database transaction."
// https://rlee.dev/practical-guide-to-fp-ts-part-3
const transaction: Database["transaction"] = (te) =>
pipe(
exec("BEGIN"),
taskEither.chainW(() => te),
taskEither.chainFirstW(() => exec("COMMIT")),
taskEither.orElse((originalError) =>
pipe(
exec("ROLLBACK"),
taskEither.matchE(taskEither.left, () =>
taskEither.left(originalError)
)
)
)
);
@enricopolanski It looks like match
is a new fold
and fold
is match
with an effect.
![Screenshot 2022-05-16 at 16 29 52](https://user-images.githubusercontent.com/66249/168616638-a93d3428-9d2f-4331-880f-36868bfc2dc4.png)