Home:ALL Converter>How to make functions work together in a single flow?

How to make functions work together in a single flow?

Ask Time:2022-05-30T04:29:18         Author:Roman Mahotskyi

Json Formatter

I recently started to learn FP by using JavaScript.

As you probably know JavaScript is a multi-paradigm language that can support FP and OO-style writing code. To write good code in a functional way usually, we need a library that can extend our possibilities to the next level.

There are planty liabraires like fp-ts, purify, effect-ts, crocks which provide us with such functionality. Most of these libraries (or all) are based on terminology and rules of category theory.

Most of these libraries (or all) have a function like a pipe which allows us to create powerful functionality from the smaller functions.

Normally, libraries show examples like

const sum = a => b => a + b
const double = a => a * 2

const doubledSum = pipe(1, sum(2), double) // 1 + 2 = 3, 3 * 2 = 6, result 6

There is nothing wrong with such examples, but they rarely have anything in common with the code of real projects.

But, usually, the production code contains Promises, Nullable data, Exceptions, and even more that should play well all together.

For all of the above, there is a special term in the FP libraries

  • Promises = Task / Future
  • Nullable = Option / Maybe
  • Exceptions = Either / Result

When these terms exist without each other (in code and in mind) everything seems to be clear. But. When you start joining them, problems arise.

I'm going to list questions that block me from writing the code and hope that people who passed this step can share their experience with me (and anyone else who has the same problems)

  1. Is it possible to write code only using pipe? Or sometimes it makes sense to use a regular function body to put if/else blocks inside (for example)
  2. How to write if/else statements in a pipe?
  3. When to use a Do notation instead of a chain/flatMap and vice versa?
  4. How to work with Do notation? I want to achieve something like:
/* This is a pseudo-code */

Do
  x <- function1()
  y <- function2()
  z <- function3()
  a <- (x, y, z) => x + y + z
  b <- (x, y, z, a) => x + y + z + a

Or in other words, I don't know how to think to use a Do notation

Any help in understanding this stuff is welcome

Author:Roman Mahotskyi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72427057/how-to-make-functions-work-together-in-a-single-flow
yy