From 2c5c9d69d6951544e7e1437e1187baba18a70522 Mon Sep 17 00:00:00 2001 From: Taylor Fausak Date: Sat, 1 May 2021 19:10:31 +0000 Subject: [PATCH] Re-order the definition of `tryVia` --- src/lib/Witch/Utility.hs | 50 ++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/src/lib/Witch/Utility.hs b/src/lib/Witch/Utility.hs index 7bad03f..db9481a 100644 --- a/src/lib/Witch/Utility.hs +++ b/src/lib/Witch/Utility.hs @@ -125,6 +125,31 @@ tryInto -> Either (TryCastException.TryCastException source target) target tryInto = TryCast.tryCast +-- | This is similar to 'via' except that it works with 'TryCast.TryCast' +-- instances instead. This function is especially convenient because juggling +-- the types in the 'TryCastException.TryCastException' can be tedious. +-- +-- > -- Avoid this: +-- > fmap (tryFrom @u) . tryInto @u +-- > +-- > -- Prefer this: +-- > tryVia @u +tryVia + :: forall u source target through + . ( Identity.Identity u ~ through + , TryCast.TryCast source through + , TryCast.TryCast through target + ) + => source + -> Either (TryCastException.TryCastException source target) target +tryVia s = case TryCast.tryCast s of + Left (TryCastException.TryCastException _ e) -> + Left $ TryCastException.TryCastException s e + Right u -> case TryCast.tryCast (u :: through) of + Left (TryCastException.TryCastException _ e) -> + Left $ TryCastException.TryCastException s e + Right t -> Right t + -- | This function can be used to implement 'TryCast.tryCast' with a function -- that returns 'Maybe'. For example: -- @@ -163,31 +188,6 @@ eitherTryCast f s = case f s of Left . TryCastException.TryCastException s . Just $ Exception.toException e Right t -> Right t --- | This is similar to 'via' except that it works with 'TryCast.TryCast' --- instances instead. This function is especially convenient because juggling --- the types in the 'TryCastException.TryCastException' can be tedious. --- --- > -- Avoid this: --- > fmap (tryFrom @u) . tryInto @u --- > --- > -- Prefer this: --- > tryVia @u -tryVia - :: forall u source target through - . ( Identity.Identity u ~ through - , TryCast.TryCast source through - , TryCast.TryCast through target - ) - => source - -> Either (TryCastException.TryCastException source target) target -tryVia s = case TryCast.tryCast s of - Left (TryCastException.TryCastException _ e) -> - Left $ TryCastException.TryCastException s e - Right u -> case TryCast.tryCast (u :: through) of - Left (TryCastException.TryCastException _ e) -> - Left $ TryCastException.TryCastException s e - Right t -> Right t - -- | This function is like 'TryCast.tryCast' except that it will throw an -- impure exception if the conversion fails. --