The name and existence of a functor or monad for chaining and completing a sequence of operations

Please forgive me, I will do my best to describe what I am looking for. I don't have a name for this, so it makes it a lot harder.

Looking at the library, such as the Folktale and monet.js I like to work with the chain mapwithout checking the zero or ifusing, for example, Maybe, Either, Task.

I am wondering if a similar construction exists to solve the following problem:

  • I have an initial input.
  • I want to build a chain of functions that work on input.
  • Each function may return a result or not return a result.
  • If the function does not return a result, call the next function in the chain.
  • As soon as the function returns, ignore the rest of the functions in the chain (similar to mapping the function on Maybe.Nothing)
  • Return the result.

In other words, I'm looking for something similar to Maybethat contains a value and displays the function on Just, but ignores the function displayed on Nothing, and you can extract the value. I am looking for something that contains an input and an initial result null. When you mapexecute a function, it runs the function on input only if resultit is NULL. If a function returns a value, it becomes the result, and any other functions that are displayed are ignored. Finally, you can extract the result.

In compulsory programming, this may look like this:

var result1 = function1(input);
if (result1) {
  return result1;
}
var result2 = function2(input);
if (result2) {
  return result2;
}
// and so on.

Instead, I would like to build something line by line

Something(input).map(function1).map(function2).result()

or

compose(result, map(compose(function2, function1))(Something(input))

? ? , , , . .

!

UPDATE

@Bergi, Maybe.orElse. ShortCircuit, , - .

import Maybe from "data.maybe";

const ShortCircuit = function(input, result) {
  this.input = input;
  this.result = result;
};

ShortCircuit.of = function(input, f) {
  return new ShortCircuit(input, Maybe.fromNullable(f(input)));
};

ShortCircuit.prototype.orElseMaybe = function(f) {
  return new ShortCircuit(this.input, this.result.orElse(() => Maybe.fromNullable(f(this.input))));
};

ShortCircuit.prototype.get = function() {
  return this.result.get();
};

export default ShortCircuit;

:

const result = ShortCircuit.of(input, f1).orElseMaybe(f2).orElseMaybe(f3).get();

.

+4
1

, , Alternative type class Haskell. 1 JS, , PureScript FantasyLand.

, Folktale, , : orElse. :

Something(input).orElse(function1).orElse(function2).get() // `get` throws when all failed

, orElse Maybe, Either, Validation Task!

getOrElse, orElse .js, , "" . Alternative, cata.

1: Googling "JS alternative" , : -)


, , promises, .catch(…), ( ES6) .

+5

Source: https://habr.com/ru/post/1619740/


All Articles