fp-ts icon indicating copy to clipboard operation
fp-ts copied to clipboard

[Question] Difference between `match` and `fold`

Open enricopolanski opened this issue 2 years ago • 4 comments

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.

enricopolanski avatar Dec 30 '21 19:12 enricopolanski

match is renamed fold, which is deprecated right now.

steida avatar Dec 30 '21 19:12 steida

@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 avatar Dec 30 '21 20:12 enricopolanski

@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)
       )
     )
   )
 );

steida avatar May 16 '22 14:05 steida

@enricopolanski It looks like match is a new fold and fold is match with an effect.

Screenshot 2022-05-16 at 16 29 52

steida avatar May 16 '22 14:05 steida