Skip to content

Instantly share code, notes, and snippets.

@benjaminweb
Last active March 7, 2024 16:53
Show Gist options
  • Save benjaminweb/0df0b7af1fef73caf47e5006b99a3a07 to your computer and use it in GitHub Desktop.
Save benjaminweb/0df0b7af1fef73caf47e5006b99a3a07 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module MyLib where
import Data.These
import Data.Text (Text)
f0 :: These [Text] Int
f0 = This ["f0 didn't work"]
-- | Produces result without error.
f1 :: These [Text] Int
f1 = That 33
f2 :: These [Text] Int
f2 = This ["f2 didn't work"]
f3 :: These [Text] Int
f3 = That 2
-- | Should return…
--
-- >>> sumAll 1 2
-- This ["a should not be less than 33"]
--
-- >>> sumAll 33 1
-- That 34
sumAll :: Int -> Int -> These [Text] Int
sumAll a b | a < 33 = This ["a should not be less than 33"]
| otherwise = That $ a + b
-- | `caller1` does not short-circuit after encountering error.
--
-- >>> caller1
-- This ["f2 didn't work"]
caller1 :: These [Text] Int
caller1 = case (f0, f1, f2) of
(This a, This b, This c) -> This $ a ++ b ++ c
(This a, This b, That c) -> This $ a ++ b
(This a, That b, This c) -> This $ a ++ c
(That a, This b, This c) -> This $ b ++ c
(That a, That b, This c) -> This c
(That a, This b, That c) -> This b
(This a, That b, That c) -> case (sumAll b c) of
This d -> This $ a ++ d
That d -> These a d
(That a, That b, That c) -> sumAll b c
-- | `caller2` does not short-circuit after encountering error.
--
-- >>> caller2
-- This ["f0 didn't work", f2 didn't work", "a should not be less than 33"]
caller2 :: These [Text] Int
caller2 = do
res1 <- f1
res3 <- f3
endResult <- sumAll res3 res1
res2 <- f2
res0 <- f0
pure $ endResult
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment