版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

1435 líneas
36 KiB

  1. import { getApplicativeMonoid } from './Applicative';
  2. import { apFirst as apFirst_, apS as apS_, apSecond as apSecond_, getApplySemigroup as getApplySemigroup_ } from './Apply';
  3. import { bind as bind_, chainFirst as chainFirst_ } from './Chain';
  4. import { tailRec } from './ChainRec';
  5. import { chainOptionK as chainOptionK_, filterOrElse as filterOrElse_, fromOption as fromOption_, fromOptionK as fromOptionK_, fromPredicate as fromPredicate_ } from './FromEither';
  6. import { flow, identity, pipe } from './function';
  7. import { bindTo as bindTo_, flap as flap_, let as let__ } from './Functor';
  8. import * as _ from './internal';
  9. import { separated } from './Separated';
  10. import { wiltDefault, witherDefault } from './Witherable';
  11. // -------------------------------------------------------------------------------------
  12. // constructors
  13. // -------------------------------------------------------------------------------------
  14. /**
  15. * Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this
  16. * structure.
  17. *
  18. * @category constructors
  19. * @since 2.0.0
  20. */
  21. export var left = _.left;
  22. /**
  23. * Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias
  24. * of this structure.
  25. *
  26. * @category constructors
  27. * @since 2.0.0
  28. */
  29. export var right = _.right;
  30. var _map = function (fa, f) { return pipe(fa, map(f)); };
  31. var _ap = function (fab, fa) { return pipe(fab, ap(fa)); };
  32. /* istanbul ignore next */
  33. var _chain = function (ma, f) { return pipe(ma, chain(f)); };
  34. /* istanbul ignore next */
  35. var _reduce = function (fa, b, f) { return pipe(fa, reduce(b, f)); };
  36. /* istanbul ignore next */
  37. var _foldMap = function (M) { return function (fa, f) {
  38. var foldMapM = foldMap(M);
  39. return pipe(fa, foldMapM(f));
  40. }; };
  41. /* istanbul ignore next */
  42. var _reduceRight = function (fa, b, f) { return pipe(fa, reduceRight(b, f)); };
  43. var _traverse = function (F) {
  44. var traverseF = traverse(F);
  45. return function (ta, f) { return pipe(ta, traverseF(f)); };
  46. };
  47. var _bimap = function (fa, f, g) { return pipe(fa, bimap(f, g)); };
  48. var _mapLeft = function (fa, f) { return pipe(fa, mapLeft(f)); };
  49. /* istanbul ignore next */
  50. var _alt = function (fa, that) { return pipe(fa, alt(that)); };
  51. /* istanbul ignore next */
  52. var _extend = function (wa, f) { return pipe(wa, extend(f)); };
  53. var _chainRec = function (a, f) {
  54. return tailRec(f(a), function (e) {
  55. return isLeft(e) ? right(left(e.left)) : isLeft(e.right) ? left(f(e.right.left)) : right(right(e.right.right));
  56. });
  57. };
  58. /**
  59. * @category type lambdas
  60. * @since 2.0.0
  61. */
  62. export var URI = 'Either';
  63. /**
  64. * @category instances
  65. * @since 2.0.0
  66. */
  67. export var getShow = function (SE, SA) { return ({
  68. show: function (ma) { return (isLeft(ma) ? "left(".concat(SE.show(ma.left), ")") : "right(".concat(SA.show(ma.right), ")")); }
  69. }); };
  70. /**
  71. * @category instances
  72. * @since 2.0.0
  73. */
  74. export var getEq = function (EL, EA) { return ({
  75. equals: function (x, y) {
  76. return x === y || (isLeft(x) ? isLeft(y) && EL.equals(x.left, y.left) : isRight(y) && EA.equals(x.right, y.right));
  77. }
  78. }); };
  79. /**
  80. * Semigroup returning the left-most non-`Left` value. If both operands are `Right`s then the inner values are
  81. * concatenated using the provided `Semigroup`
  82. *
  83. * @example
  84. * import { getSemigroup, left, right } from 'fp-ts/Either'
  85. * import { SemigroupSum } from 'fp-ts/number'
  86. *
  87. * const S = getSemigroup<string, number>(SemigroupSum)
  88. * assert.deepStrictEqual(S.concat(left('a'), left('b')), left('a'))
  89. * assert.deepStrictEqual(S.concat(left('a'), right(2)), right(2))
  90. * assert.deepStrictEqual(S.concat(right(1), left('b')), right(1))
  91. * assert.deepStrictEqual(S.concat(right(1), right(2)), right(3))
  92. *
  93. * @category instances
  94. * @since 2.0.0
  95. */
  96. export var getSemigroup = function (S) { return ({
  97. concat: function (x, y) { return (isLeft(y) ? x : isLeft(x) ? y : right(S.concat(x.right, y.right))); }
  98. }); };
  99. /**
  100. * Builds a `Compactable` instance for `Either` given `Monoid` for the left side.
  101. *
  102. * @category filtering
  103. * @since 2.10.0
  104. */
  105. export var getCompactable = function (M) {
  106. var empty = left(M.empty);
  107. return {
  108. URI: URI,
  109. _E: undefined,
  110. compact: function (ma) { return (isLeft(ma) ? ma : ma.right._tag === 'None' ? empty : right(ma.right.value)); },
  111. separate: function (ma) {
  112. return isLeft(ma)
  113. ? separated(ma, ma)
  114. : isLeft(ma.right)
  115. ? separated(right(ma.right.left), empty)
  116. : separated(empty, right(ma.right.right));
  117. }
  118. };
  119. };
  120. /**
  121. * Builds a `Filterable` instance for `Either` given `Monoid` for the left side
  122. *
  123. * @category filtering
  124. * @since 2.10.0
  125. */
  126. export var getFilterable = function (M) {
  127. var empty = left(M.empty);
  128. var _a = getCompactable(M), compact = _a.compact, separate = _a.separate;
  129. var filter = function (ma, predicate) {
  130. return isLeft(ma) ? ma : predicate(ma.right) ? ma : empty;
  131. };
  132. var partition = function (ma, p) {
  133. return isLeft(ma)
  134. ? separated(ma, ma)
  135. : p(ma.right)
  136. ? separated(empty, right(ma.right))
  137. : separated(right(ma.right), empty);
  138. };
  139. return {
  140. URI: URI,
  141. _E: undefined,
  142. map: _map,
  143. compact: compact,
  144. separate: separate,
  145. filter: filter,
  146. filterMap: function (ma, f) {
  147. if (isLeft(ma)) {
  148. return ma;
  149. }
  150. var ob = f(ma.right);
  151. return ob._tag === 'None' ? empty : right(ob.value);
  152. },
  153. partition: partition,
  154. partitionMap: function (ma, f) {
  155. if (isLeft(ma)) {
  156. return separated(ma, ma);
  157. }
  158. var e = f(ma.right);
  159. return isLeft(e) ? separated(right(e.left), empty) : separated(empty, right(e.right));
  160. }
  161. };
  162. };
  163. /**
  164. * Builds `Witherable` instance for `Either` given `Monoid` for the left side
  165. *
  166. * @category filtering
  167. * @since 2.0.0
  168. */
  169. export var getWitherable = function (M) {
  170. var F_ = getFilterable(M);
  171. var C = getCompactable(M);
  172. return {
  173. URI: URI,
  174. _E: undefined,
  175. map: _map,
  176. compact: F_.compact,
  177. separate: F_.separate,
  178. filter: F_.filter,
  179. filterMap: F_.filterMap,
  180. partition: F_.partition,
  181. partitionMap: F_.partitionMap,
  182. traverse: _traverse,
  183. sequence: sequence,
  184. reduce: _reduce,
  185. foldMap: _foldMap,
  186. reduceRight: _reduceRight,
  187. wither: witherDefault(Traversable, C),
  188. wilt: wiltDefault(Traversable, C)
  189. };
  190. };
  191. /**
  192. * The default [`Applicative`](#applicative) instance returns the first error, if you want to
  193. * get all errors you need to provide a way to concatenate them via a `Semigroup`.
  194. *
  195. * @example
  196. * import * as A from 'fp-ts/Apply'
  197. * import * as E from 'fp-ts/Either'
  198. * import { pipe } from 'fp-ts/function'
  199. * import * as S from 'fp-ts/Semigroup'
  200. * import * as string from 'fp-ts/string'
  201. *
  202. * const parseString = (u: unknown): E.Either<string, string> =>
  203. * typeof u === 'string' ? E.right(u) : E.left('not a string')
  204. *
  205. * const parseNumber = (u: unknown): E.Either<string, number> =>
  206. * typeof u === 'number' ? E.right(u) : E.left('not a number')
  207. *
  208. * interface Person {
  209. * readonly name: string
  210. * readonly age: number
  211. * }
  212. *
  213. * const parsePerson = (
  214. * input: Record<string, unknown>
  215. * ): E.Either<string, Person> =>
  216. * pipe(
  217. * E.Do,
  218. * E.apS('name', parseString(input.name)),
  219. * E.apS('age', parseNumber(input.age))
  220. * )
  221. *
  222. * assert.deepStrictEqual(parsePerson({}), E.left('not a string')) // <= first error
  223. *
  224. * const Applicative = E.getApplicativeValidation(
  225. * pipe(string.Semigroup, S.intercalate(', '))
  226. * )
  227. *
  228. * const apS = A.apS(Applicative)
  229. *
  230. * const parsePersonAll = (
  231. * input: Record<string, unknown>
  232. * ): E.Either<string, Person> =>
  233. * pipe(
  234. * E.Do,
  235. * apS('name', parseString(input.name)),
  236. * apS('age', parseNumber(input.age))
  237. * )
  238. *
  239. * assert.deepStrictEqual(parsePersonAll({}), E.left('not a string, not a number')) // <= all errors
  240. *
  241. * @category error handling
  242. * @since 2.7.0
  243. */
  244. export var getApplicativeValidation = function (SE) { return ({
  245. URI: URI,
  246. _E: undefined,
  247. map: _map,
  248. ap: function (fab, fa) {
  249. return isLeft(fab)
  250. ? isLeft(fa)
  251. ? left(SE.concat(fab.left, fa.left))
  252. : fab
  253. : isLeft(fa)
  254. ? fa
  255. : right(fab.right(fa.right));
  256. },
  257. of: of
  258. }); };
  259. /**
  260. * The default [`Alt`](#alt) instance returns the last error, if you want to
  261. * get all errors you need to provide a way to concatenate them via a `Semigroup`.
  262. *
  263. * @example
  264. * import * as E from 'fp-ts/Either'
  265. * import { pipe } from 'fp-ts/function'
  266. * import * as S from 'fp-ts/Semigroup'
  267. * import * as string from 'fp-ts/string'
  268. *
  269. * const parseString = (u: unknown): E.Either<string, string> =>
  270. * typeof u === 'string' ? E.right(u) : E.left('not a string')
  271. *
  272. * const parseNumber = (u: unknown): E.Either<string, number> =>
  273. * typeof u === 'number' ? E.right(u) : E.left('not a number')
  274. *
  275. * const parse = (u: unknown): E.Either<string, string | number> =>
  276. * pipe(
  277. * parseString(u),
  278. * E.alt<string, string | number>(() => parseNumber(u))
  279. * )
  280. *
  281. * assert.deepStrictEqual(parse(true), E.left('not a number')) // <= last error
  282. *
  283. * const Alt = E.getAltValidation(pipe(string.Semigroup, S.intercalate(', ')))
  284. *
  285. * const parseAll = (u: unknown): E.Either<string, string | number> =>
  286. * Alt.alt<string | number>(parseString(u), () => parseNumber(u))
  287. *
  288. * assert.deepStrictEqual(parseAll(true), E.left('not a string, not a number')) // <= all errors
  289. *
  290. * @category error handling
  291. * @since 2.7.0
  292. */
  293. export var getAltValidation = function (SE) { return ({
  294. URI: URI,
  295. _E: undefined,
  296. map: _map,
  297. alt: function (me, that) {
  298. if (isRight(me)) {
  299. return me;
  300. }
  301. var ea = that();
  302. return isLeft(ea) ? left(SE.concat(me.left, ea.left)) : ea;
  303. }
  304. }); };
  305. /**
  306. * @category mapping
  307. * @since 2.0.0
  308. */
  309. export var map = function (f) { return function (fa) {
  310. return isLeft(fa) ? fa : right(f(fa.right));
  311. }; };
  312. /**
  313. * @category instances
  314. * @since 2.7.0
  315. */
  316. export var Functor = {
  317. URI: URI,
  318. map: _map
  319. };
  320. /**
  321. * @category constructors
  322. * @since 2.7.0
  323. */
  324. export var of = right;
  325. /**
  326. * @category instances
  327. * @since 2.10.0
  328. */
  329. export var Pointed = {
  330. URI: URI,
  331. of: of
  332. };
  333. /**
  334. * Less strict version of [`ap`](#ap).
  335. *
  336. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  337. *
  338. * @since 2.8.0
  339. */
  340. export var apW = function (fa) { return function (fab) {
  341. return isLeft(fab) ? fab : isLeft(fa) ? fa : right(fab.right(fa.right));
  342. }; };
  343. /**
  344. * @since 2.0.0
  345. */
  346. export var ap = apW;
  347. /**
  348. * @category instances
  349. * @since 2.10.0
  350. */
  351. export var Apply = {
  352. URI: URI,
  353. map: _map,
  354. ap: _ap
  355. };
  356. /**
  357. * @category instances
  358. * @since 2.7.0
  359. */
  360. export var Applicative = {
  361. URI: URI,
  362. map: _map,
  363. ap: _ap,
  364. of: of
  365. };
  366. /**
  367. * Less strict version of [`chain`](#chain).
  368. *
  369. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  370. *
  371. * @example
  372. * import * as E from 'fp-ts/Either'
  373. * import { pipe } from 'fp-ts/function'
  374. *
  375. * const e1: E.Either<string, number> = E.right(1)
  376. * const e2: E.Either<number, number> = E.right(2)
  377. *
  378. * export const result1 = pipe(
  379. * // @ts-expect-error
  380. * e1,
  381. * E.chain(() => e2)
  382. * )
  383. *
  384. * // merged error types -----v-------------v
  385. * // const result2: E.Either<string | number, number>
  386. * export const result2 = pipe(
  387. * e1, // no error
  388. * E.chainW(() => e2)
  389. * )
  390. *
  391. * @category sequencing
  392. * @since 2.6.0
  393. */
  394. export var chainW = function (f) {
  395. return function (ma) {
  396. return isLeft(ma) ? ma : f(ma.right);
  397. };
  398. };
  399. /**
  400. * Composes computations in sequence, using the return value of one computation to determine the next computation.
  401. *
  402. * @category sequencing
  403. * @since 2.0.0
  404. */
  405. export var chain = chainW;
  406. /**
  407. * @category instances
  408. * @since 2.10.0
  409. */
  410. export var Chain = {
  411. URI: URI,
  412. map: _map,
  413. ap: _ap,
  414. chain: _chain
  415. };
  416. /**
  417. * @category instances
  418. * @since 2.7.0
  419. */
  420. export var Monad = {
  421. URI: URI,
  422. map: _map,
  423. ap: _ap,
  424. of: of,
  425. chain: _chain
  426. };
  427. /**
  428. * Left-associative fold of a structure.
  429. *
  430. * @example
  431. * import { pipe } from 'fp-ts/function'
  432. * import * as E from 'fp-ts/Either'
  433. *
  434. * const startWith = 'prefix'
  435. * const concat = (a: string, b: string) => `${a}:${b}`
  436. *
  437. * assert.deepStrictEqual(
  438. * pipe(E.right('a'), E.reduce(startWith, concat)),
  439. * 'prefix:a'
  440. * )
  441. *
  442. * assert.deepStrictEqual(
  443. * pipe(E.left('e'), E.reduce(startWith, concat)),
  444. * 'prefix'
  445. * )
  446. *
  447. * @category folding
  448. * @since 2.0.0
  449. */
  450. export var reduce = function (b, f) { return function (fa) {
  451. return isLeft(fa) ? b : f(b, fa.right);
  452. }; };
  453. /**
  454. * Map each element of the structure to a monoid, and combine the results.
  455. *
  456. * @example
  457. * import { pipe } from 'fp-ts/function'
  458. * import * as E from 'fp-ts/Either'
  459. * import * as S from 'fp-ts/string'
  460. *
  461. * const yell = (a: string) => `${a}!`
  462. *
  463. * assert.deepStrictEqual(
  464. * pipe(E.right('a'), E.foldMap(S.Monoid)(yell)),
  465. * 'a!'
  466. * )
  467. *
  468. * assert.deepStrictEqual(
  469. * pipe(E.left('e'), E.foldMap(S.Monoid)(yell)),
  470. * S.Monoid.empty
  471. * )
  472. *
  473. * @category folding
  474. * @since 2.0.0
  475. */
  476. export var foldMap = function (M) { return function (f) { return function (fa) {
  477. return isLeft(fa) ? M.empty : f(fa.right);
  478. }; }; };
  479. /**
  480. * Right-associative fold of a structure.
  481. *
  482. * @example
  483. * import { pipe } from 'fp-ts/function'
  484. * import * as E from 'fp-ts/Either'
  485. *
  486. * const startWith = 'postfix'
  487. * const concat = (a: string, b: string) => `${a}:${b}`
  488. *
  489. * assert.deepStrictEqual(
  490. * pipe(E.right('a'), E.reduceRight(startWith, concat)),
  491. * 'a:postfix'
  492. * )
  493. *
  494. * assert.deepStrictEqual(
  495. * pipe(E.left('e'), E.reduceRight(startWith, concat)),
  496. * 'postfix'
  497. * )
  498. *
  499. * @category folding
  500. * @since 2.0.0
  501. */
  502. export var reduceRight = function (b, f) { return function (fa) {
  503. return isLeft(fa) ? b : f(fa.right, b);
  504. }; };
  505. /**
  506. * @category instances
  507. * @since 2.7.0
  508. */
  509. export var Foldable = {
  510. URI: URI,
  511. reduce: _reduce,
  512. foldMap: _foldMap,
  513. reduceRight: _reduceRight
  514. };
  515. /**
  516. * Map each element of a structure to an action, evaluate these actions from left to right, and collect the results.
  517. *
  518. * @example
  519. * import { pipe } from 'fp-ts/function'
  520. * import * as RA from 'fp-ts/ReadonlyArray'
  521. * import * as E from 'fp-ts/Either'
  522. * import * as O from 'fp-ts/Option'
  523. *
  524. * assert.deepStrictEqual(
  525. * pipe(E.right(['a']), E.traverse(O.Applicative)(RA.head)),
  526. * O.some(E.right('a'))
  527. * )
  528. *
  529. * assert.deepStrictEqual(
  530. * pipe(E.right([]), E.traverse(O.Applicative)(RA.head)),
  531. * O.none
  532. * )
  533. *
  534. * @category traversing
  535. * @since 2.6.3
  536. */
  537. export var traverse = function (F) {
  538. return function (f) {
  539. return function (ta) {
  540. return isLeft(ta) ? F.of(left(ta.left)) : F.map(f(ta.right), right);
  541. };
  542. };
  543. };
  544. /**
  545. * Evaluate each monadic action in the structure from left to right, and collect the results.
  546. *
  547. * @example
  548. * import { pipe } from 'fp-ts/function'
  549. * import * as E from 'fp-ts/Either'
  550. * import * as O from 'fp-ts/Option'
  551. *
  552. * assert.deepStrictEqual(
  553. * pipe(E.right(O.some('a')), E.sequence(O.Applicative)),
  554. * O.some(E.right('a'))
  555. * )
  556. *
  557. * assert.deepStrictEqual(
  558. * pipe(E.right(O.none), E.sequence(O.Applicative)),
  559. * O.none
  560. * )
  561. *
  562. * @category traversing
  563. * @since 2.6.3
  564. */
  565. export var sequence = function (F) {
  566. return function (ma) {
  567. return isLeft(ma) ? F.of(left(ma.left)) : F.map(ma.right, right);
  568. };
  569. };
  570. /**
  571. * @category instances
  572. * @since 2.7.0
  573. */
  574. export var Traversable = {
  575. URI: URI,
  576. map: _map,
  577. reduce: _reduce,
  578. foldMap: _foldMap,
  579. reduceRight: _reduceRight,
  580. traverse: _traverse,
  581. sequence: sequence
  582. };
  583. /**
  584. * Map a pair of functions over the two type arguments of the bifunctor.
  585. *
  586. * @category mapping
  587. * @since 2.0.0
  588. */
  589. export var bimap = function (f, g) { return function (fa) {
  590. return isLeft(fa) ? left(f(fa.left)) : right(g(fa.right));
  591. }; };
  592. /**
  593. * Map a function over the first type argument of a bifunctor.
  594. *
  595. * @category error handling
  596. * @since 2.0.0
  597. */
  598. export var mapLeft = function (f) { return function (fa) {
  599. return isLeft(fa) ? left(f(fa.left)) : fa;
  600. }; };
  601. /**
  602. * @category instances
  603. * @since 2.7.0
  604. */
  605. export var Bifunctor = {
  606. URI: URI,
  607. bimap: _bimap,
  608. mapLeft: _mapLeft
  609. };
  610. /**
  611. * Less strict version of [`alt`](#alt).
  612. *
  613. * The `W` suffix (short for **W**idening) means that the error and the return types will be merged.
  614. *
  615. * @category error handling
  616. * @since 2.9.0
  617. */
  618. export var altW = function (that) { return function (fa) {
  619. return isLeft(fa) ? that() : fa;
  620. }; };
  621. /**
  622. * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to
  623. * types of kind `* -> *`.
  624. *
  625. * In case of `Either` returns the left-most non-`Left` value (or the right-most `Left` value if both values are `Left`).
  626. *
  627. * | x | y | pipe(x, alt(() => y) |
  628. * | -------- | -------- | -------------------- |
  629. * | left(a) | left(b) | left(b) |
  630. * | left(a) | right(2) | right(2) |
  631. * | right(1) | left(b) | right(1) |
  632. * | right(1) | right(2) | right(1) |
  633. *
  634. * @example
  635. * import * as E from 'fp-ts/Either'
  636. * import { pipe } from 'fp-ts/function'
  637. *
  638. * assert.deepStrictEqual(
  639. * pipe(
  640. * E.left('a'),
  641. * E.alt(() => E.left('b'))
  642. * ),
  643. * E.left('b')
  644. * )
  645. * assert.deepStrictEqual(
  646. * pipe(
  647. * E.left('a'),
  648. * E.alt(() => E.right(2))
  649. * ),
  650. * E.right(2)
  651. * )
  652. * assert.deepStrictEqual(
  653. * pipe(
  654. * E.right(1),
  655. * E.alt(() => E.left('b'))
  656. * ),
  657. * E.right(1)
  658. * )
  659. * assert.deepStrictEqual(
  660. * pipe(
  661. * E.right(1),
  662. * E.alt(() => E.right(2))
  663. * ),
  664. * E.right(1)
  665. * )
  666. *
  667. * @category error handling
  668. * @since 2.0.0
  669. */
  670. export var alt = altW;
  671. /**
  672. * @category instances
  673. * @since 2.7.0
  674. */
  675. export var Alt = {
  676. URI: URI,
  677. map: _map,
  678. alt: _alt
  679. };
  680. /**
  681. * @since 2.0.0
  682. */
  683. export var extend = function (f) { return function (wa) {
  684. return isLeft(wa) ? wa : right(f(wa));
  685. }; };
  686. /**
  687. * @category instances
  688. * @since 2.7.0
  689. */
  690. export var Extend = {
  691. URI: URI,
  692. map: _map,
  693. extend: _extend
  694. };
  695. /**
  696. * @category instances
  697. * @since 2.7.0
  698. */
  699. export var ChainRec = {
  700. URI: URI,
  701. map: _map,
  702. ap: _ap,
  703. chain: _chain,
  704. chainRec: _chainRec
  705. };
  706. /**
  707. * @since 2.6.3
  708. */
  709. export var throwError = left;
  710. /**
  711. * @category instances
  712. * @since 2.7.0
  713. */
  714. export var MonadThrow = {
  715. URI: URI,
  716. map: _map,
  717. ap: _ap,
  718. of: of,
  719. chain: _chain,
  720. throwError: throwError
  721. };
  722. /**
  723. * @category instances
  724. * @since 2.10.0
  725. */
  726. export var FromEither = {
  727. URI: URI,
  728. fromEither: identity
  729. };
  730. /**
  731. * @example
  732. * import { fromPredicate, left, right } from 'fp-ts/Either'
  733. * import { pipe } from 'fp-ts/function'
  734. *
  735. * assert.deepStrictEqual(
  736. * pipe(
  737. * 1,
  738. * fromPredicate(
  739. * (n) => n > 0,
  740. * () => 'error'
  741. * )
  742. * ),
  743. * right(1)
  744. * )
  745. * assert.deepStrictEqual(
  746. * pipe(
  747. * -1,
  748. * fromPredicate(
  749. * (n) => n > 0,
  750. * () => 'error'
  751. * )
  752. * ),
  753. * left('error')
  754. * )
  755. *
  756. * @category lifting
  757. * @since 2.0.0
  758. */
  759. export var fromPredicate = /*#__PURE__*/ fromPredicate_(FromEither);
  760. // -------------------------------------------------------------------------------------
  761. // conversions
  762. // -------------------------------------------------------------------------------------
  763. /**
  764. * @example
  765. * import * as E from 'fp-ts/Either'
  766. * import { pipe } from 'fp-ts/function'
  767. * import * as O from 'fp-ts/Option'
  768. *
  769. * assert.deepStrictEqual(
  770. * pipe(
  771. * O.some(1),
  772. * E.fromOption(() => 'error')
  773. * ),
  774. * E.right(1)
  775. * )
  776. * assert.deepStrictEqual(
  777. * pipe(
  778. * O.none,
  779. * E.fromOption(() => 'error')
  780. * ),
  781. * E.left('error')
  782. * )
  783. *
  784. * @category conversions
  785. * @since 2.0.0
  786. */
  787. export var fromOption =
  788. /*#__PURE__*/ fromOption_(FromEither);
  789. // -------------------------------------------------------------------------------------
  790. // refinements
  791. // -------------------------------------------------------------------------------------
  792. /**
  793. * Returns `true` if the either is an instance of `Left`, `false` otherwise.
  794. *
  795. * @category refinements
  796. * @since 2.0.0
  797. */
  798. export var isLeft = _.isLeft;
  799. /**
  800. * Returns `true` if the either is an instance of `Right`, `false` otherwise.
  801. *
  802. * @category refinements
  803. * @since 2.0.0
  804. */
  805. export var isRight = _.isRight;
  806. /**
  807. * Less strict version of [`match`](#match).
  808. *
  809. * The `W` suffix (short for **W**idening) means that the handler return types will be merged.
  810. *
  811. * @category pattern matching
  812. * @since 2.10.0
  813. */
  814. export var matchW = function (onLeft, onRight) {
  815. return function (ma) {
  816. return isLeft(ma) ? onLeft(ma.left) : onRight(ma.right);
  817. };
  818. };
  819. /**
  820. * Alias of [`matchW`](#matchw).
  821. *
  822. * @category pattern matching
  823. * @since 2.10.0
  824. */
  825. export var foldW = matchW;
  826. /**
  827. * Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the first function,
  828. * if the value is a `Right` the inner value is applied to the second function.
  829. *
  830. * @example
  831. * import { match, left, right } from 'fp-ts/Either'
  832. * import { pipe } from 'fp-ts/function'
  833. *
  834. * function onLeft(errors: Array<string>): string {
  835. * return `Errors: ${errors.join(', ')}`
  836. * }
  837. *
  838. * function onRight(value: number): string {
  839. * return `Ok: ${value}`
  840. * }
  841. *
  842. * assert.strictEqual(
  843. * pipe(
  844. * right(1),
  845. * match(onLeft, onRight)
  846. * ),
  847. * 'Ok: 1'
  848. * )
  849. * assert.strictEqual(
  850. * pipe(
  851. * left(['error 1', 'error 2']),
  852. * match(onLeft, onRight)
  853. * ),
  854. * 'Errors: error 1, error 2'
  855. * )
  856. *
  857. * @category pattern matching
  858. * @since 2.10.0
  859. */
  860. export var match = matchW;
  861. /**
  862. * Alias of [`match`](#match).
  863. *
  864. * @category pattern matching
  865. * @since 2.0.0
  866. */
  867. export var fold = match;
  868. /**
  869. * Less strict version of [`getOrElse`](#getorelse).
  870. *
  871. * The `W` suffix (short for **W**idening) means that the handler return type will be merged.
  872. *
  873. * @category error handling
  874. * @since 2.6.0
  875. */
  876. export var getOrElseW = function (onLeft) {
  877. return function (ma) {
  878. return isLeft(ma) ? onLeft(ma.left) : ma.right;
  879. };
  880. };
  881. /**
  882. * Returns the wrapped value if it's a `Right` or a default value if is a `Left`.
  883. *
  884. * @example
  885. * import { getOrElse, left, right } from 'fp-ts/Either'
  886. * import { pipe } from 'fp-ts/function'
  887. *
  888. * assert.deepStrictEqual(
  889. * pipe(
  890. * right(1),
  891. * getOrElse(() => 0)
  892. * ),
  893. * 1
  894. * )
  895. * assert.deepStrictEqual(
  896. * pipe(
  897. * left('error'),
  898. * getOrElse(() => 0)
  899. * ),
  900. * 0
  901. * )
  902. *
  903. * @category error handling
  904. * @since 2.0.0
  905. */
  906. export var getOrElse = getOrElseW;
  907. // -------------------------------------------------------------------------------------
  908. // combinators
  909. // -------------------------------------------------------------------------------------
  910. /**
  911. * @category mapping
  912. * @since 2.10.0
  913. */
  914. export var flap = /*#__PURE__*/ flap_(Functor);
  915. /**
  916. * Combine two effectful actions, keeping only the result of the first.
  917. *
  918. * @since 2.0.0
  919. */
  920. export var apFirst = /*#__PURE__*/ apFirst_(Apply);
  921. /**
  922. * Less strict version of [`apFirst`](#apfirst)
  923. *
  924. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  925. *
  926. * @since 2.12.0
  927. */
  928. export var apFirstW = apFirst;
  929. /**
  930. * Combine two effectful actions, keeping only the result of the second.
  931. *
  932. * @since 2.0.0
  933. */
  934. export var apSecond = /*#__PURE__*/ apSecond_(Apply);
  935. /**
  936. * Less strict version of [`apSecond`](#apsecond)
  937. *
  938. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  939. *
  940. * @since 2.12.0
  941. */
  942. export var apSecondW = apSecond;
  943. /**
  944. * Composes computations in sequence, using the return value of one computation to determine the next computation and
  945. * keeping only the result of the first.
  946. *
  947. * @category sequencing
  948. * @since 2.0.0
  949. */
  950. export var chainFirst =
  951. /*#__PURE__*/ chainFirst_(Chain);
  952. /**
  953. * Less strict version of [`chainFirst`](#chainfirst)
  954. *
  955. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  956. *
  957. * @category sequencing
  958. * @since 2.8.0
  959. */
  960. export var chainFirstW = chainFirst;
  961. /**
  962. * Less strict version of [`flatten`](#flatten).
  963. *
  964. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  965. *
  966. * @category sequencing
  967. * @since 2.11.0
  968. */
  969. export var flattenW =
  970. /*#__PURE__*/ chainW(identity);
  971. /**
  972. * The `flatten` function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level.
  973. *
  974. * @example
  975. * import * as E from 'fp-ts/Either'
  976. *
  977. * assert.deepStrictEqual(E.flatten(E.right(E.right('a'))), E.right('a'))
  978. * assert.deepStrictEqual(E.flatten(E.right(E.left('e'))), E.left('e'))
  979. * assert.deepStrictEqual(E.flatten(E.left('e')), E.left('e'))
  980. *
  981. * @category sequencing
  982. * @since 2.0.0
  983. */
  984. export var flatten = flattenW;
  985. /**
  986. * @since 2.0.0
  987. */
  988. export var duplicate = /*#__PURE__*/ extend(identity);
  989. /**
  990. * @category lifting
  991. * @since 2.10.0
  992. */
  993. export var fromOptionK =
  994. /*#__PURE__*/ fromOptionK_(FromEither);
  995. /**
  996. * @category sequencing
  997. * @since 2.11.0
  998. */
  999. export var chainOptionK = /*#__PURE__*/ chainOptionK_(FromEither, Chain);
  1000. /**
  1001. * @example
  1002. * import * as E from 'fp-ts/Either'
  1003. * import { pipe } from 'fp-ts/function'
  1004. *
  1005. * assert.deepStrictEqual(
  1006. * pipe(
  1007. * E.right(1),
  1008. * E.filterOrElse(
  1009. * (n) => n > 0,
  1010. * () => 'error'
  1011. * )
  1012. * ),
  1013. * E.right(1)
  1014. * )
  1015. * assert.deepStrictEqual(
  1016. * pipe(
  1017. * E.right(-1),
  1018. * E.filterOrElse(
  1019. * (n) => n > 0,
  1020. * () => 'error'
  1021. * )
  1022. * ),
  1023. * E.left('error')
  1024. * )
  1025. * assert.deepStrictEqual(
  1026. * pipe(
  1027. * E.left('a'),
  1028. * E.filterOrElse(
  1029. * (n) => n > 0,
  1030. * () => 'error'
  1031. * )
  1032. * ),
  1033. * E.left('a')
  1034. * )
  1035. *
  1036. * @category filtering
  1037. * @since 2.0.0
  1038. */
  1039. export var filterOrElse = /*#__PURE__*/ filterOrElse_(FromEither, Chain);
  1040. /**
  1041. * Less strict version of [`filterOrElse`](#filterorelse).
  1042. *
  1043. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  1044. *
  1045. * @category filtering
  1046. * @since 2.9.0
  1047. */
  1048. export var filterOrElseW = filterOrElse;
  1049. /**
  1050. * Returns a `Right` if is a `Left` (and vice versa).
  1051. *
  1052. * @since 2.0.0
  1053. */
  1054. export var swap = function (ma) { return (isLeft(ma) ? right(ma.left) : left(ma.right)); };
  1055. /**
  1056. * Less strict version of [`orElse`](#orelse).
  1057. *
  1058. * The `W` suffix (short for **W**idening) means that the return types will be merged.
  1059. *
  1060. * @category error handling
  1061. * @since 2.10.0
  1062. */
  1063. export var orElseW = function (onLeft) {
  1064. return function (ma) {
  1065. return isLeft(ma) ? onLeft(ma.left) : ma;
  1066. };
  1067. };
  1068. /**
  1069. * Useful for recovering from errors.
  1070. *
  1071. * @category error handling
  1072. * @since 2.0.0
  1073. */
  1074. export var orElse = orElseW;
  1075. /**
  1076. * Takes a default and a nullable value, if the value is not nully, turn it into a `Right`, if the value is nully use
  1077. * the provided default as a `Left`.
  1078. *
  1079. * @example
  1080. * import { fromNullable, left, right } from 'fp-ts/Either'
  1081. *
  1082. * const parse = fromNullable('nully')
  1083. *
  1084. * assert.deepStrictEqual(parse(1), right(1))
  1085. * assert.deepStrictEqual(parse(null), left('nully'))
  1086. *
  1087. * @category conversions
  1088. * @since 2.0.0
  1089. */
  1090. export var fromNullable = function (e) {
  1091. return function (a) {
  1092. return a == null ? left(e) : right(a);
  1093. };
  1094. };
  1095. /**
  1096. * Constructs a new `Either` from a function that might throw.
  1097. *
  1098. * See also [`tryCatchK`](#trycatchk).
  1099. *
  1100. * @example
  1101. * import * as E from 'fp-ts/Either'
  1102. *
  1103. * const unsafeHead = <A>(as: ReadonlyArray<A>): A => {
  1104. * if (as.length > 0) {
  1105. * return as[0]
  1106. * } else {
  1107. * throw new Error('empty array')
  1108. * }
  1109. * }
  1110. *
  1111. * const head = <A>(as: ReadonlyArray<A>): E.Either<Error, A> =>
  1112. * E.tryCatch(() => unsafeHead(as), e => (e instanceof Error ? e : new Error('unknown error')))
  1113. *
  1114. * assert.deepStrictEqual(head([]), E.left(new Error('empty array')))
  1115. * assert.deepStrictEqual(head([1, 2, 3]), E.right(1))
  1116. *
  1117. * @category interop
  1118. * @since 2.0.0
  1119. */
  1120. export var tryCatch = function (f, onThrow) {
  1121. try {
  1122. return right(f());
  1123. }
  1124. catch (e) {
  1125. return left(onThrow(e));
  1126. }
  1127. };
  1128. /**
  1129. * Converts a function that may throw to one returning a `Either`.
  1130. *
  1131. * @category interop
  1132. * @since 2.10.0
  1133. */
  1134. export var tryCatchK = function (f, onThrow) {
  1135. return function () {
  1136. var a = [];
  1137. for (var _i = 0; _i < arguments.length; _i++) {
  1138. a[_i] = arguments[_i];
  1139. }
  1140. return tryCatch(function () { return f.apply(void 0, a); }, onThrow);
  1141. };
  1142. };
  1143. /**
  1144. * @category lifting
  1145. * @since 2.9.0
  1146. */
  1147. export var fromNullableK = function (e) {
  1148. var from = fromNullable(e);
  1149. return function (f) { return flow(f, from); };
  1150. };
  1151. /**
  1152. * @category sequencing
  1153. * @since 2.9.0
  1154. */
  1155. export var chainNullableK = function (e) {
  1156. var from = fromNullableK(e);
  1157. return function (f) { return chain(from(f)); };
  1158. };
  1159. /**
  1160. * @category conversions
  1161. * @since 2.10.0
  1162. */
  1163. export var toUnion = /*#__PURE__*/ foldW(identity, identity);
  1164. // -------------------------------------------------------------------------------------
  1165. // utils
  1166. // -------------------------------------------------------------------------------------
  1167. /**
  1168. * Default value for the `onError` argument of `tryCatch`
  1169. *
  1170. * @since 2.0.0
  1171. */
  1172. export function toError(e) {
  1173. return e instanceof Error ? e : new Error(String(e));
  1174. }
  1175. export function elem(E) {
  1176. return function (a, ma) {
  1177. if (ma === undefined) {
  1178. var elemE_1 = elem(E);
  1179. return function (ma) { return elemE_1(a, ma); };
  1180. }
  1181. return isLeft(ma) ? false : E.equals(a, ma.right);
  1182. };
  1183. }
  1184. /**
  1185. * Returns `false` if `Left` or returns the result of the application of the given predicate to the `Right` value.
  1186. *
  1187. * @example
  1188. * import { exists, left, right } from 'fp-ts/Either'
  1189. *
  1190. * const gt2 = exists((n: number) => n > 2)
  1191. *
  1192. * assert.strictEqual(gt2(left('a')), false)
  1193. * assert.strictEqual(gt2(right(1)), false)
  1194. * assert.strictEqual(gt2(right(3)), true)
  1195. *
  1196. * @since 2.0.0
  1197. */
  1198. export var exists = function (predicate) {
  1199. return function (ma) {
  1200. return isLeft(ma) ? false : predicate(ma.right);
  1201. };
  1202. };
  1203. // -------------------------------------------------------------------------------------
  1204. // do notation
  1205. // -------------------------------------------------------------------------------------
  1206. /**
  1207. * @category do notation
  1208. * @since 2.9.0
  1209. */
  1210. export var Do = /*#__PURE__*/ of(_.emptyRecord);
  1211. /**
  1212. * @category do notation
  1213. * @since 2.8.0
  1214. */
  1215. export var bindTo = /*#__PURE__*/ bindTo_(Functor);
  1216. var let_ = /*#__PURE__*/ let__(Functor);
  1217. export {
  1218. /**
  1219. * @category do notation
  1220. * @since 2.13.0
  1221. */
  1222. let_ as let };
  1223. /**
  1224. * @category do notation
  1225. * @since 2.8.0
  1226. */
  1227. export var bind = /*#__PURE__*/ bind_(Chain);
  1228. /**
  1229. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  1230. *
  1231. * @category do notation
  1232. * @since 2.8.0
  1233. */
  1234. export var bindW = bind;
  1235. /**
  1236. * @category do notation
  1237. * @since 2.8.0
  1238. */
  1239. export var apS = /*#__PURE__*/ apS_(Apply);
  1240. /**
  1241. * Less strict version of [`apS`](#aps).
  1242. *
  1243. * The `W` suffix (short for **W**idening) means that the error types will be merged.
  1244. *
  1245. * @category do notation
  1246. * @since 2.8.0
  1247. */
  1248. export var apSW = apS;
  1249. /**
  1250. * @since 2.11.0
  1251. */
  1252. export var ApT = /*#__PURE__*/ of(_.emptyReadonlyArray);
  1253. // -------------------------------------------------------------------------------------
  1254. // array utils
  1255. // -------------------------------------------------------------------------------------
  1256. /**
  1257. * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`.
  1258. *
  1259. * @category traversing
  1260. * @since 2.11.0
  1261. */
  1262. export var traverseReadonlyNonEmptyArrayWithIndex = function (f) {
  1263. return function (as) {
  1264. var e = f(0, _.head(as));
  1265. if (isLeft(e)) {
  1266. return e;
  1267. }
  1268. var out = [e.right];
  1269. for (var i = 1; i < as.length; i++) {
  1270. var e_1 = f(i, as[i]);
  1271. if (isLeft(e_1)) {
  1272. return e_1;
  1273. }
  1274. out.push(e_1.right);
  1275. }
  1276. return right(out);
  1277. };
  1278. };
  1279. /**
  1280. * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.
  1281. *
  1282. * @category traversing
  1283. * @since 2.11.0
  1284. */
  1285. export var traverseReadonlyArrayWithIndex = function (f) {
  1286. var g = traverseReadonlyNonEmptyArrayWithIndex(f);
  1287. return function (as) { return (_.isNonEmpty(as) ? g(as) : ApT); };
  1288. };
  1289. /**
  1290. * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.
  1291. *
  1292. * @category traversing
  1293. * @since 2.9.0
  1294. */
  1295. export var traverseArrayWithIndex = traverseReadonlyArrayWithIndex;
  1296. /**
  1297. * Equivalent to `ReadonlyArray#traverse(Applicative)`.
  1298. *
  1299. * @category traversing
  1300. * @since 2.9.0
  1301. */
  1302. export var traverseArray = function (f) { return traverseReadonlyArrayWithIndex(function (_, a) { return f(a); }); };
  1303. /**
  1304. * Equivalent to `ReadonlyArray#sequence(Applicative)`.
  1305. *
  1306. * @category traversing
  1307. * @since 2.9.0
  1308. */
  1309. export var sequenceArray =
  1310. /*#__PURE__*/ traverseArray(identity);
  1311. /**
  1312. * Use [`parse`](./Json.ts.html#parse) instead.
  1313. *
  1314. * @category zone of death
  1315. * @since 2.0.0
  1316. * @deprecated
  1317. */
  1318. export function parseJSON(s, onError) {
  1319. return tryCatch(function () { return JSON.parse(s); }, onError);
  1320. }
  1321. /**
  1322. * Use [`stringify`](./Json.ts.html#stringify) instead.
  1323. *
  1324. * @category zone of death
  1325. * @since 2.0.0
  1326. * @deprecated
  1327. */
  1328. export var stringifyJSON = function (u, onError) {
  1329. return tryCatch(function () {
  1330. var s = JSON.stringify(u);
  1331. if (typeof s !== 'string') {
  1332. throw new Error('Converting unsupported structure to JSON');
  1333. }
  1334. return s;
  1335. }, onError);
  1336. };
  1337. /**
  1338. * This instance is deprecated, use small, specific instances instead.
  1339. * For example if a function needs a `Functor` instance, pass `E.Functor` instead of `E.either`
  1340. * (where `E` is from `import E from 'fp-ts/Either'`)
  1341. *
  1342. * @category zone of death
  1343. * @since 2.0.0
  1344. * @deprecated
  1345. */
  1346. export var either = {
  1347. URI: URI,
  1348. map: _map,
  1349. of: of,
  1350. ap: _ap,
  1351. chain: _chain,
  1352. reduce: _reduce,
  1353. foldMap: _foldMap,
  1354. reduceRight: _reduceRight,
  1355. traverse: _traverse,
  1356. sequence: sequence,
  1357. bimap: _bimap,
  1358. mapLeft: _mapLeft,
  1359. alt: _alt,
  1360. extend: _extend,
  1361. chainRec: _chainRec,
  1362. throwError: throwError
  1363. };
  1364. /**
  1365. * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.
  1366. *
  1367. * Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values
  1368. * are concatenated using the provided `Semigroup`
  1369. *
  1370. * @category zone of death
  1371. * @since 2.0.0
  1372. * @deprecated
  1373. */
  1374. export var getApplySemigroup =
  1375. /*#__PURE__*/ getApplySemigroup_(Apply);
  1376. /**
  1377. * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.
  1378. *
  1379. * @category zone of death
  1380. * @since 2.0.0
  1381. * @deprecated
  1382. */
  1383. export var getApplyMonoid =
  1384. /*#__PURE__*/ getApplicativeMonoid(Applicative);
  1385. /**
  1386. * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.
  1387. *
  1388. * @category zone of death
  1389. * @since 2.0.0
  1390. * @deprecated
  1391. */
  1392. export var getValidationSemigroup = function (SE, SA) {
  1393. return getApplySemigroup_(getApplicativeValidation(SE))(SA);
  1394. };
  1395. /**
  1396. * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.
  1397. *
  1398. * @category zone of death
  1399. * @since 2.0.0
  1400. * @deprecated
  1401. */
  1402. export var getValidationMonoid = function (SE, MA) {
  1403. return getApplicativeMonoid(getApplicativeValidation(SE))(MA);
  1404. };
  1405. /**
  1406. * Use [`getApplicativeValidation`](#getapplicativevalidation) and [`getAltValidation`](#getaltvalidation) instead.
  1407. *
  1408. * @category zone of death
  1409. * @since 2.0.0
  1410. * @deprecated
  1411. */
  1412. export function getValidation(SE) {
  1413. var ap = getApplicativeValidation(SE).ap;
  1414. var alt = getAltValidation(SE).alt;
  1415. return {
  1416. URI: URI,
  1417. _E: undefined,
  1418. map: _map,
  1419. of: of,
  1420. chain: _chain,
  1421. bimap: _bimap,
  1422. mapLeft: _mapLeft,
  1423. reduce: _reduce,
  1424. foldMap: _foldMap,
  1425. reduceRight: _reduceRight,
  1426. extend: _extend,
  1427. traverse: _traverse,
  1428. sequence: sequence,
  1429. chainRec: _chainRec,
  1430. throwError: throwError,
  1431. ap: ap,
  1432. alt: alt
  1433. };
  1434. }