Skip to content

Commit 2f12ae8

Browse files
Add lazy versions of fromRight and fromLeft (#59)
1 parent 36ba0fa commit 2f12ae8

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/Data/Either.purs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,13 +280,31 @@ fromLeft :: forall a b. a -> Either a b -> a
280280
fromLeft _ (Left a) = a
281281
fromLeft default _ = default
282282

283+
-- | Similar to `fromLeft` but for use in cases where the default value may be
284+
-- | expensive to compute. As PureScript is not lazy, the standard `fromLeft`
285+
-- | has to evaluate the default value before returning the result,
286+
-- | whereas here the value is only computed when the `Either` is known
287+
-- | to be `Right`.
288+
fromLeft' :: forall a b. (Unit -> a) -> Either a b -> a
289+
fromLeft' _ (Left a) = a
290+
fromLeft' default _ = default unit
291+
283292
-- | A function that extracts the value from the `Right` data constructor.
284293
-- | The first argument is a default value, which will be returned in the
285294
-- | case where a `Left` is passed to `fromRight`.
286295
fromRight :: forall a b. b -> Either a b -> b
287296
fromRight _ (Right b) = b
288297
fromRight default _ = default
289298

299+
-- | Similar to `fromRight` but for use in cases where the default value may be
300+
-- | expensive to compute. As PureScript is not lazy, the standard `fromRight`
301+
-- | has to evaluate the default value before returning the result,
302+
-- | whereas here the value is only computed when the `Either` is known
303+
-- | to be `Left`.
304+
fromRight' :: forall a b. (Unit -> b) -> Either a b -> b
305+
fromRight' _ (Right b) = b
306+
fromRight' default _ = default unit
307+
290308
-- | Takes a default and a `Maybe` value, if the value is a `Just`, turn it into
291309
-- | a `Right`, if the value is a `Nothing` use the provided default as a `Left`
292310
-- |

0 commit comments

Comments
 (0)