diff --git a/index.js b/index.js index b9fa21fa..288559c3 100644 --- a/index.js +++ b/index.js @@ -2362,6 +2362,52 @@ impl: either }; + //# fromLeft :: a -> Either a b -> a + //. + //. Takes a default value and an Either, and returns the Left value + //. if the Either is a Left; the default value otherwise. + //. + //. See also [`fromRight`](#fromRight). + //. + //. ```javascript + //. > S.fromLeft (0) (S.Left (42)) + //. 42 + //. + //. > S.fromLeft (0) (S.Right (42)) + //. 0 + //. ``` + function fromLeft(x) { + return either (I) (K (x)); + } + _.fromLeft = { + consts: {}, + types: [a, $.Either (a) (b), a], + impl: fromLeft + }; + + //# fromRight :: b -> Either a b -> b + //. + //. Takes a default value and an Either, and returns the Right value + //. if the Either is a Right; the default value otherwise. + //. + //. See also [`fromLeft`](#fromLeft). + //. + //. ```javascript + //. > S.fromRight (0) (S.Right (42)) + //. 42 + //. + //. > S.fromRight (0) (S.Left (42)) + //. 0 + //. ``` + function fromRight(x) { + return either (K (x)) (I); + } + _.fromRight = { + consts: {}, + types: [b, $.Either (a) (b), b], + impl: fromRight + }; + //# fromEither :: b -> Either a b -> b //. //. Takes a default value and an Either, and returns the Right value diff --git a/test/fromLeft.js b/test/fromLeft.js new file mode 100644 index 00000000..be94c2e6 --- /dev/null +++ b/test/fromLeft.js @@ -0,0 +1,15 @@ +'use strict'; + +const S = require ('..'); + +const eq = require ('./internal/eq'); + + +test ('fromLeft', () => { + + eq (S.show (S.fromLeft)) ('fromLeft :: a -> Either a b -> a'); + + eq (S.fromLeft (0) (S.Left (42))) (42); + eq (S.fromLeft (0) (S.Right (42))) (0); + +}); diff --git a/test/fromRight.js b/test/fromRight.js new file mode 100644 index 00000000..8ddfa725 --- /dev/null +++ b/test/fromRight.js @@ -0,0 +1,15 @@ +'use strict'; + +const S = require ('..'); + +const eq = require ('./internal/eq'); + + +test ('fromRight', () => { + + eq (S.show (S.fromRight)) ('fromRight :: b -> Either a b -> b'); + + eq (S.fromRight (0) (S.Left (42))) (0); + eq (S.fromRight (0) (S.Right (42))) (42); + +});