{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ViewPatterns #-}

module PossehlAnalyticsPrelude
  ( -- * Text conversions
    Text,
    ByteString,
    Word8,
    fmt,
    textToString,
    stringToText,
    stringToBytesUtf8,
    showToText,
    textToBytesUtf8,
    textToBytesUtf8Lazy,
    bytesToTextUtf8,
    bytesToTextUtf8Lazy,
    bytesToTextUtf8Lenient,
    bytesToTextUtf8LenientLazy,
    bytesToTextUtf8Unsafe,
    bytesToTextUtf8UnsafeLazy,
    toStrict,
    toLazy,
    toStrictBytes,
    toLazyBytes,
    charToWordUnsafe,

    -- * IO
    putStrLn,
    putStderrLn,
    exitWithMessage,

    -- * WIP code
    todo,

    -- * Records
    HasField,

    -- * Control flow
    doAs,
    (&),
    (<&>),
    (<|>),
    foldMap1,
    foldMap',
    join,
    when,
    unless,
    guard,
    ExceptT (..),
    runExceptT,
    MonadThrow,
    throwM,
    MonadIO,
    liftIO,
    MonadReader,
    asks,
    Bifunctor,
    first,
    second,
    bimap,
    both,
    foldMap,
    fold,
    foldl',
    fromMaybe,
    mapMaybe,
    findMaybe,
    Traversable,
    for,
    for_,
    traverse,
    traverse_,
    traverseFold,
    traverseFold1,
    traverseFoldDefault,
    MonadTrans,
    lift,

    -- * Data types
    Coercible,
    coerce,
    Proxy (Proxy),
    Map,
    annotate,
    Validation (Success, Failure),
    failure,
    successes,
    failures,
    traverseValidate,
    traverseValidateM,
    traverseValidateM_,
    eitherToValidation,
    eitherToListValidation,
    validationToEither,
    These (This, That, These),
    eitherToThese,
    eitherToListThese,
    validationToThese,
    thenThese,
    thenValidate,
    thenValidateM,
    NonEmpty ((:|)),
    pattern IsEmpty,
    pattern IsNonEmpty,
    singleton,
    nonEmpty,
    nonEmptyDef,
    overNonEmpty,
    zipNonEmpty,
    zipWithNonEmpty,
    zip3NonEmpty,
    zipWith3NonEmpty,
    zip4NonEmpty,
    toList,
    toNonEmptyDefault,
    lengthNatural,
    maximum1,
    minimum1,
    maximumBy1,
    minimumBy1,
    Vector,
    Generic,
    Lift,
    Semigroup,
    sconcat,
    Monoid,
    mconcat,
    ifTrue,
    ifExists,
    Void,
    absurd,
    Identity (Identity, runIdentity),
    Natural,
    intToNatural,
    Scientific,
    Contravariant,
    contramap,
    (>$<),
    (>&<),
    Profunctor,
    dimap,
    lmap,
    rmap,
    Semigroupoid,
    Category,
    (>>>),
    (&>>),
    Any,

    -- * Enum definition
    inverseFunction,
    inverseMap,
    enumerateAll,

    -- * Map helpers
    mapFromListOn,
    mapFromListOnMerge,

    -- * Error handling
    HasCallStack,
    module Data.Error,
  )
where

import Control.Applicative ((<|>))
import Control.Category (Category, (>>>))
import Control.Foldl.NonEmpty qualified as Foldl1
import Control.Monad (guard, join, unless, when)
import Control.Monad.Catch (MonadThrow (throwM))
import Control.Monad.Except
  ( ExceptT (..),
    runExceptT,
  )
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Identity (Identity (Identity))
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans (MonadTrans (lift))
import Data.Bifunctor (Bifunctor, bimap, first, second)
import Data.ByteString
  ( ByteString,
  )
import Data.ByteString.Lazy qualified
import Data.Char qualified
import Data.Coerce (Coercible, coerce)
import Data.Data (Proxy (Proxy))
import Data.Error
import Data.Foldable (Foldable (foldMap', toList), fold, foldl', for_, sequenceA_, traverse_)
import Data.Foldable qualified as Foldable
import Data.Function ((&))
import Data.Functor ((<&>))
import Data.Functor.Contravariant (Contravariant (contramap), (>$<))
import Data.Functor.Identity (Identity (runIdentity))
import Data.List (zip4)
import Data.List.NonEmpty (NonEmpty ((:|)), nonEmpty)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Map.Strict
  ( Map,
  )
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Maybe qualified as Maybe
import Data.Profunctor (Profunctor, dimap, lmap, rmap)
import Data.Scientific (Scientific)
import Data.Semigroup (sconcat)
import Data.Semigroup.Foldable (Foldable1 (fold1), foldMap1)
import Data.Semigroup.Traversable (Traversable1)
import Data.Semigroupoid (Semigroupoid (o))
import Data.Text
  ( Text,
  )
import Data.Text qualified
import Data.Text.Encoding qualified
import Data.Text.Encoding.Error qualified
import Data.Text.Lazy qualified
import Data.Text.Lazy.Encoding qualified
import Data.These (These (That, These, This))
import Data.Traversable (for)
import Data.Vector (Vector)
import Data.Void (Void, absurd)
import Data.Word (Word8)
import GHC.Exception (errorCallWithCallStackException)
import GHC.Exts (Any, RuntimeRep, TYPE, raise#)
import GHC.Generics (Generic)
import GHC.Natural (Natural)
import GHC.Records (HasField)
import GHC.Stack (HasCallStack)
import GHC.Utils.Encoding.UTF8 qualified as GHC
import Language.Haskell.TH.Syntax (Lift)
import PyF (fmt)
import System.Exit qualified
import System.IO qualified
import Validation
  ( Validation (Failure, Success),
    eitherToValidation,
    failure,
    failures,
    successes,
    validationToEither,
  )

-- | Mark a `do`-block with the type of the Monad/Applicativ it uses.
-- Only intended for reading ease and making code easier to understand,
-- especially do-blocks that use unconventional monads (like Maybe or List).
--
-- Example:
--
-- @
-- doAs @Maybe $ do
--  a <- Just 'a'
--  b <- Just 'b'
--  pure (a, b)
-- @
doAs :: forall m a. m a -> m a
doAs :: forall {k} (m :: k -> Type) (a :: k). m a -> m a
doAs = m a -> m a
forall a. a -> a
id

-- | Forward-applying 'contramap', like '&'/'$' and '<&>'/'<$>' but for '>$<'.
(>&<) :: (Contravariant f) => f b -> (a -> b) -> f a
>&< :: forall (f :: Type -> Type) b a.
Contravariant f =>
f b -> (a -> b) -> f a
(>&<) = ((a -> b) -> f b -> f a) -> f b -> (a -> b) -> f a
forall a b c. (a -> b -> c) -> b -> a -> c
flip (a -> b) -> f b -> f a
forall a' a. (a' -> a) -> f a -> f a'
forall (f :: Type -> Type) a' a.
Contravariant f =>
(a' -> a) -> f a -> f a'
contramap

infixl 5 >&<

-- | Forward semigroupoid application. The same as '(>>>)', but 'Semigroupoid' is not a superclass of 'Category' (yet).
--
-- Specialized examples:
--
-- @
-- for functions : (a -> b) -> (b -> c) -> (a -> c)
-- for Folds: Fold a b -> Fold b c -> Fold a c
-- @
(&>>) :: (Semigroupoid s) => s a b -> s b c -> s a c
&>> :: forall {k} (s :: k -> k -> Type) (a :: k) (b :: k) (c :: k).
Semigroupoid s =>
s a b -> s b c -> s a c
(&>>) = (s b c -> s a b -> s a c) -> s a b -> s b c -> s a c
forall a b c. (a -> b -> c) -> b -> a -> c
flip s b c -> s a b -> s a c
forall (j :: k) (k1 :: k) (i :: k). s j k1 -> s i j -> s i k1
forall {k} (c :: k -> k -> Type) (j :: k) (k1 :: k) (i :: k).
Semigroupoid c =>
c j k1 -> c i j -> c i k1
Data.Semigroupoid.o

-- like >>>
infixr 1 &>>

-- | encode a Text to a UTF-8 encoded Bytestring
textToBytesUtf8 :: Text -> ByteString
textToBytesUtf8 :: Text -> ByteString
textToBytesUtf8 = Text -> ByteString
Data.Text.Encoding.encodeUtf8

-- | encode a lazy Text to a UTF-8 encoded lazy Bytestring
textToBytesUtf8Lazy :: Data.Text.Lazy.Text -> Data.ByteString.Lazy.ByteString
textToBytesUtf8Lazy :: Text -> ByteString
textToBytesUtf8Lazy = Text -> ByteString
Data.Text.Lazy.Encoding.encodeUtf8

bytesToTextUtf8 :: ByteString -> Either Error Text
bytesToTextUtf8 :: ByteString -> Either Error Text
bytesToTextUtf8 = (UnicodeException -> Error)
-> Either UnicodeException Text -> Either Error Text
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: Type -> Type -> Type) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first UnicodeException -> Error
forall exc. Exception exc => exc -> Error
exceptionToError (Either UnicodeException Text -> Either Error Text)
-> (ByteString -> Either UnicodeException Text)
-> ByteString
-> Either Error Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either UnicodeException Text
Data.Text.Encoding.decodeUtf8'

bytesToTextUtf8Lazy :: Data.ByteString.Lazy.ByteString -> Either Error Data.Text.Lazy.Text
bytesToTextUtf8Lazy :: ByteString -> Either Error Text
bytesToTextUtf8Lazy = (UnicodeException -> Error)
-> Either UnicodeException Text -> Either Error Text
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: Type -> Type -> Type) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first UnicodeException -> Error
forall exc. Exception exc => exc -> Error
exceptionToError (Either UnicodeException Text -> Either Error Text)
-> (ByteString -> Either UnicodeException Text)
-> ByteString
-> Either Error Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either UnicodeException Text
Data.Text.Lazy.Encoding.decodeUtf8'

-- | decode a Text from a ByteString that is assumed to be UTF-8 (crash if that is not the case)
bytesToTextUtf8Unsafe :: ByteString -> Text
bytesToTextUtf8Unsafe :: ByteString -> Text
bytesToTextUtf8Unsafe = ByteString -> Text
Data.Text.Encoding.decodeUtf8

-- | decode a Text from a ByteString that is assumed to be UTF-8 (crash if that is not the case)
bytesToTextUtf8UnsafeLazy :: Data.ByteString.Lazy.ByteString -> Data.Text.Lazy.Text
bytesToTextUtf8UnsafeLazy :: ByteString -> Text
bytesToTextUtf8UnsafeLazy = ByteString -> Text
Data.Text.Lazy.Encoding.decodeUtf8

-- | decode a Text from a ByteString that is assumed to be UTF-8,
-- replace non-UTF-8 characters with the replacment char U+FFFD.
bytesToTextUtf8Lenient :: Data.ByteString.ByteString -> Data.Text.Text
bytesToTextUtf8Lenient :: ByteString -> Text
bytesToTextUtf8Lenient =
  OnDecodeError -> ByteString -> Text
Data.Text.Encoding.decodeUtf8With OnDecodeError
Data.Text.Encoding.Error.lenientDecode

-- | decode a lazy Text from a lazy ByteString that is assumed to be UTF-8,
-- replace non-UTF-8 characters with the replacment char U+FFFD.
bytesToTextUtf8LenientLazy :: Data.ByteString.Lazy.ByteString -> Data.Text.Lazy.Text
bytesToTextUtf8LenientLazy :: ByteString -> Text
bytesToTextUtf8LenientLazy =
  OnDecodeError -> ByteString -> Text
Data.Text.Lazy.Encoding.decodeUtf8With OnDecodeError
Data.Text.Encoding.Error.lenientDecode

-- | Make a lazy 'Text' strict.
toStrict :: Data.Text.Lazy.Text -> Text
toStrict :: Text -> Text
toStrict = Text -> Text
Data.Text.Lazy.toStrict

-- | Make a strict 'Text' lazy.
toLazy :: Text -> Data.Text.Lazy.Text
toLazy :: Text -> Text
toLazy = Text -> Text
Data.Text.Lazy.fromStrict

-- | Make a lazy 'ByteString' strict.
toStrictBytes :: Data.ByteString.Lazy.ByteString -> ByteString
toStrictBytes :: ByteString -> ByteString
toStrictBytes = ByteString -> ByteString
Data.ByteString.Lazy.toStrict

-- | Make a strict 'ByteString' lazy.
toLazyBytes :: ByteString -> Data.ByteString.Lazy.ByteString
toLazyBytes :: ByteString -> ByteString
toLazyBytes = ByteString -> ByteString
Data.ByteString.Lazy.fromStrict

-- | Convert a (performant) 'Text' into an (imperformant) list-of-char 'String'.
--
-- Some libraries (like @time@ or @network-uri@) still use the `String` as their interface. We only want to convert to string at the edges, otherwise use 'Text'.
--
-- ATTN: Don’t use `String` in code if you can avoid it, prefer `Text` instead.
textToString :: Text -> String
textToString :: Text -> String
textToString = Text -> String
Data.Text.unpack

-- | Convert an (imperformant) list-of-char 'String' into a (performant) 'Text' .
--
-- Some libraries (like @time@ or @network-uri@) still use the `String` as their interface. We want to convert 'String' to 'Text' as soon as possible and only use 'Text' in our code.
--
-- ATTN: Don’t use `String` in code if you can avoid it, prefer `Text` instead.
stringToText :: String -> Text
stringToText :: String -> Text
stringToText = String -> Text
Data.Text.pack

-- | Encode a String to an UTF-8 encoded Bytestring
--
-- ATTN: Don’t use `String` in code if you can avoid it, prefer `Text` instead.
stringToBytesUtf8 :: String -> ByteString
stringToBytesUtf8 :: String -> ByteString
stringToBytesUtf8 = String -> ByteString
GHC.utf8EncodeByteString

-- | Like `show`, but generate a 'Text'
--
-- ATTN: This goes via `String` and thus is fairly inefficient.
-- We should add a good display library at one point.
--
-- ATTN: unlike `show`, this forces the whole @'a
-- so only use if you want to display the whole thing.
showToText :: (Show a) => a -> Text
showToText :: forall a. Show a => a -> Text
showToText = String -> Text
stringToText (String -> Text) -> (a -> String) -> a -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> String
forall a. Show a => a -> String
show

-- | Unsafe conversion between 'Char' and 'Word8'. This is a no-op and
-- silently truncates to 8 bits Chars > '\255'. It is provided as
-- convenience for ByteString construction.
--
-- Use if you want to get the 'Word8' representation of a character literal.
-- Don’t use on arbitrary characters!
--
-- >>> charToWordUnsafe ','
-- 44
charToWordUnsafe :: Char -> Word8
{-# INLINE charToWordUnsafe #-}
charToWordUnsafe :: Char -> Word8
charToWordUnsafe = Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Word8) -> (Char -> Int) -> Char -> Word8
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Int
Data.Char.ord

pattern IsEmpty :: [a]
pattern $mIsEmpty :: forall {r} {a}. [a] -> ((# #) -> r) -> ((# #) -> r) -> r
$bIsEmpty :: forall a. [a]
IsEmpty <- (null -> True)
  where
    IsEmpty = []

pattern IsNonEmpty :: NonEmpty a -> [a]
pattern $mIsNonEmpty :: forall {r} {a}. [a] -> (NonEmpty a -> r) -> ((# #) -> r) -> r
$bIsNonEmpty :: forall a. NonEmpty a -> [a]
IsNonEmpty n <- (nonEmpty -> Just n)
  where
    IsNonEmpty NonEmpty a
n = NonEmpty a -> [a]
forall a. NonEmpty a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList NonEmpty a
n

{-# COMPLETE IsEmpty, IsNonEmpty #-}

-- | Single element in a (non-empty) list.
singleton :: a -> NonEmpty a
singleton :: forall a. a -> NonEmpty a
singleton a
a = a
a a -> [a] -> NonEmpty a
forall a. a -> [a] -> NonEmpty a
:| []

-- | If the given list is empty, use the given default element and return a non-empty list.
nonEmptyDef :: a -> [a] -> NonEmpty a
nonEmptyDef :: forall a. a -> [a] -> NonEmpty a
nonEmptyDef a
def [a]
xs =
  [a]
xs [a] -> ([a] -> Maybe (NonEmpty a)) -> Maybe (NonEmpty a)
forall a b. a -> (a -> b) -> b
& [a] -> Maybe (NonEmpty a)
forall a. [a] -> Maybe (NonEmpty a)
nonEmpty Maybe (NonEmpty a)
-> (Maybe (NonEmpty a) -> NonEmpty a) -> NonEmpty a
forall a b. a -> (a -> b) -> b
& \case
    Maybe (NonEmpty a)
Nothing -> a
def a -> [a] -> NonEmpty a
forall a. a -> [a] -> NonEmpty a
:| []
    Just NonEmpty a
ne -> NonEmpty a
ne

-- | Construct a non-empty list, given a default value if the ist list was empty.
toNonEmptyDefault :: a -> [a] -> NonEmpty a
toNonEmptyDefault :: forall a. a -> [a] -> NonEmpty a
toNonEmptyDefault a
def [a]
xs = case [a]
xs of
  [] -> a
def a -> [a] -> NonEmpty a
forall a. a -> [a] -> NonEmpty a
:| []
  (a
x : [a]
xs') -> a
x a -> [a] -> NonEmpty a
forall a. a -> [a] -> NonEmpty a
:| [a]
xs'

-- | If the list is not empty, run the given function with a NonEmpty list, otherwise just return []
overNonEmpty :: (Applicative f) => (NonEmpty a -> f [b]) -> [a] -> f [b]
overNonEmpty :: forall (f :: Type -> Type) a b.
Applicative f =>
(NonEmpty a -> f [b]) -> [a] -> f [b]
overNonEmpty NonEmpty a -> f [b]
f [a]
xs = case [a]
xs of
  [a]
IsEmpty -> [b] -> f [b]
forall a. a -> f a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure []
  IsNonEmpty NonEmpty a
xs' -> NonEmpty a -> f [b]
f NonEmpty a
xs'

-- | Zip two non-empty lists.
zipNonEmpty :: NonEmpty a -> NonEmpty b -> NonEmpty (a, b)
{-# INLINE zipNonEmpty #-}
zipNonEmpty :: forall a b. NonEmpty a -> NonEmpty b -> NonEmpty (a, b)
zipNonEmpty ~(a
a :| [a]
as) ~(b
b :| [b]
bs) = (a
a, b
b) (a, b) -> [(a, b)] -> NonEmpty (a, b)
forall a. a -> [a] -> NonEmpty a
:| [a] -> [b] -> [(a, b)]
forall a b. [a] -> [b] -> [(a, b)]
zip [a]
as [b]
bs

-- | Zip two non-empty lists, combining them with the given function
zipWithNonEmpty :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
{-# INLINE zipWithNonEmpty #-}
zipWithNonEmpty :: forall a b c.
(a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
zipWithNonEmpty = (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
forall a b c.
(a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
NonEmpty.zipWith

-- | Zip three non-empty lists.
zip3NonEmpty :: NonEmpty a -> NonEmpty b -> NonEmpty c -> NonEmpty (a, b, c)
{-# INLINE zip3NonEmpty #-}
zip3NonEmpty :: forall a b c.
NonEmpty a -> NonEmpty b -> NonEmpty c -> NonEmpty (a, b, c)
zip3NonEmpty ~(a
a :| [a]
as) ~(b
b :| [b]
bs) ~(c
c :| [c]
cs) = (a
a, b
b, c
c) (a, b, c) -> [(a, b, c)] -> NonEmpty (a, b, c)
forall a. a -> [a] -> NonEmpty a
:| [a] -> [b] -> [c] -> [(a, b, c)]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 [a]
as [b]
bs [c]
cs

-- | Zip three non-empty lists, combining them with the given function
zipWith3NonEmpty :: (a -> b -> c -> d) -> NonEmpty a -> NonEmpty b -> NonEmpty c -> NonEmpty d
{-# INLINE zipWith3NonEmpty #-}
zipWith3NonEmpty :: forall a b c d.
(a -> b -> c -> d)
-> NonEmpty a -> NonEmpty b -> NonEmpty c -> NonEmpty d
zipWith3NonEmpty a -> b -> c -> d
f ~(a
x :| [a]
xs) ~(b
y :| [b]
ys) ~(c
z :| [c]
zs) = a -> b -> c -> d
f a
x b
y c
z d -> [d] -> NonEmpty d
forall a. a -> [a] -> NonEmpty a
:| (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3 a -> b -> c -> d
f [a]
xs [b]
ys [c]
zs

-- | Zip four non-empty lists
zip4NonEmpty :: NonEmpty a -> NonEmpty b -> NonEmpty c -> NonEmpty d -> NonEmpty (a, b, c, d)
{-# INLINE zip4NonEmpty #-}
zip4NonEmpty :: forall a b c d.
NonEmpty a
-> NonEmpty b -> NonEmpty c -> NonEmpty d -> NonEmpty (a, b, c, d)
zip4NonEmpty ~(a
a :| [a]
as) ~(b
b :| [b]
bs) ~(c
c :| [c]
cs) ~(d
d :| [d]
ds) = (a
a, b
b, c
c, d
d) (a, b, c, d) -> [(a, b, c, d)] -> NonEmpty (a, b, c, d)
forall a. a -> [a] -> NonEmpty a
:| [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
forall a b c d. [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
zip4 [a]
as [b]
bs [c]
cs [d]
ds

-- | We don’t want to use Foldable’s `length`, because it is too polymorphic and can lead to bugs.
-- Only list-y things should have a length.
class (Foldable f) => Lengthy f

instance Lengthy []

instance Lengthy NonEmpty

instance Lengthy Vector

lengthNatural :: (Lengthy f) => f a -> Natural
lengthNatural :: forall (f :: Type -> Type) a. Lengthy f => f a -> Natural
lengthNatural f a
xs =
  f a
xs
    f a -> (f a -> Int) -> Int
forall a b. a -> (a -> b) -> b
& f a -> Int
forall a. f a -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
Foldable.length
    -- length can never be negative or something went really, really wrong
    Int -> (Int -> Natural) -> Natural
forall a b. a -> (a -> b) -> b
& forall a b. (Integral a, Num b) => a -> b
fromIntegral @Int @Natural

-- | @O(n)@. Get the maximum element from a non-empty structure (strict).
maximum1 :: (Foldable1 f, Ord a) => f a -> a
maximum1 :: forall (f :: Type -> Type) a. (Foldable1 f, Ord a) => f a -> a
maximum1 = Fold1 a a -> f a -> a
forall (f :: Type -> Type) a b.
Foldable1 f =>
Fold1 a b -> f a -> b
Foldl1.fold1 Fold1 a a
forall a. Ord a => Fold1 a a
Foldl1.maximum

-- | @O(n)@. Get the maximum element from a non-empty structure, using the given comparator (strict).
maximumBy1 :: (Foldable1 f) => (a -> a -> Ordering) -> f a -> a
maximumBy1 :: forall (f :: Type -> Type) a.
Foldable1 f =>
(a -> a -> Ordering) -> f a -> a
maximumBy1 a -> a -> Ordering
f = Fold1 a a -> f a -> a
forall (f :: Type -> Type) a b.
Foldable1 f =>
Fold1 a b -> f a -> b
Foldl1.fold1 ((a -> a -> Ordering) -> Fold1 a a
forall a. (a -> a -> Ordering) -> Fold1 a a
Foldl1.maximumBy a -> a -> Ordering
f)

-- | @O(n)@. Get the minimum element from a non-empty structure (strict).
minimum1 :: (Foldable1 f, Ord a) => f a -> a
minimum1 :: forall (f :: Type -> Type) a. (Foldable1 f, Ord a) => f a -> a
minimum1 = Fold1 a a -> f a -> a
forall (f :: Type -> Type) a b.
Foldable1 f =>
Fold1 a b -> f a -> b
Foldl1.fold1 Fold1 a a
forall a. Ord a => Fold1 a a
Foldl1.minimum

-- | @O(n)@. Get the minimum element from a non-empty structure, using the given comparator (strict).
minimumBy1 :: (Foldable1 f) => (a -> a -> Ordering) -> f a -> a
minimumBy1 :: forall (f :: Type -> Type) a.
Foldable1 f =>
(a -> a -> Ordering) -> f a -> a
minimumBy1 a -> a -> Ordering
f = Fold1 a a -> f a -> a
forall (f :: Type -> Type) a b.
Foldable1 f =>
Fold1 a b -> f a -> b
Foldl1.fold1 ((a -> a -> Ordering) -> Fold1 a a
forall a. (a -> a -> Ordering) -> Fold1 a a
Foldl1.minimumBy a -> a -> Ordering
f)

-- | Annotate a 'Maybe' with an error message and turn it into an 'Either'.
annotate :: err -> Maybe a -> Either err a
annotate :: forall err a. err -> Maybe a -> Either err a
annotate err
err = \case
  Maybe a
Nothing -> err -> Either err a
forall a b. a -> Either a b
Left err
err
  Just a
a -> a -> Either err a
forall a b. b -> Either a b
Right a
a

-- | Map the same function over both sides of a Bifunctor (e.g. a tuple).
both :: (Bifunctor bi) => (a -> b) -> bi a a -> bi b b
both :: forall (bi :: Type -> Type -> Type) a b.
Bifunctor bi =>
(a -> b) -> bi a a -> bi b b
both a -> b
f = (a -> b) -> (a -> b) -> bi a a -> bi b b
forall a b c d. (a -> b) -> (c -> d) -> bi a c -> bi b d
forall (p :: Type -> Type -> Type) a b c d.
Bifunctor p =>
(a -> b) -> (c -> d) -> p a c -> p b d
bimap a -> b
f a -> b
f

-- | Find the first element for which pred returns `Just a`, and return the `a`.
--
-- Example:
-- @
-- >>> :set -XTypeApplications
-- >>> import qualified Text.Read
--
-- >>> findMaybe (Text.Read.readMaybe @Int) ["foo"]
-- Nothing
-- >>> findMaybe (Text.Read.readMaybe @Int) ["foo", "34.40", "34", "abc"]
-- Just 34
findMaybe :: (Foldable t) => (a -> Maybe b) -> t a -> Maybe b
findMaybe :: forall (t :: Type -> Type) a b.
Foldable t =>
(a -> Maybe b) -> t a -> Maybe b
findMaybe a -> Maybe b
mPred t a
list =
  let pred' :: a -> Bool
pred' a
x = Maybe b -> Bool
forall a. Maybe a -> Bool
Maybe.isJust (Maybe b -> Bool) -> Maybe b -> Bool
forall a b. (a -> b) -> a -> b
$ a -> Maybe b
mPred a
x
   in case (a -> Bool) -> t a -> Maybe a
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Maybe a
Foldable.find a -> Bool
pred' t a
list of
        Just a
a -> a -> Maybe b
mPred a
a
        Maybe a
Nothing -> Maybe b
forall a. Maybe a
Nothing

-- | 'traverse' with a function returning 'Either' and collect all errors that happen, if they happen.
--
-- Does not shortcut on error, so will always traverse the whole list/'Traversable' structure.
--
-- This is a useful error handling function in many circumstances,
-- because it won’t only return the first error that happens, but rather all of them.
traverseValidate :: forall t a err b. (Traversable t) => (a -> Either err b) -> t a -> Either (NonEmpty err) (t b)
traverseValidate :: forall (t :: Type -> Type) a err b.
Traversable t =>
(a -> Either err b) -> t a -> Either (NonEmpty err) (t b)
traverseValidate a -> Either err b
f t a
as =
  t a
as
    t a
-> (t a -> Validation (NonEmpty err) (t b))
-> Validation (NonEmpty err) (t b)
forall a b. a -> (a -> b) -> b
& forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse @t @(Validation _) (Either err b -> Validation (NonEmpty err) b
forall a c. Either a c -> Validation (NonEmpty a) c
eitherToListValidation (Either err b -> Validation (NonEmpty err) b)
-> (a -> Either err b) -> a -> Validation (NonEmpty err) b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Either err b
f)
    Validation (NonEmpty err) (t b)
-> (Validation (NonEmpty err) (t b) -> Either (NonEmpty err) (t b))
-> Either (NonEmpty err) (t b)
forall a b. a -> (a -> b) -> b
& Validation (NonEmpty err) (t b) -> Either (NonEmpty err) (t b)
forall e a. Validation e a -> Either e a
validationToEither

-- | 'traverse' with a function returning 'm Either' and collect all errors that happen, if they happen.
--
-- Does not shortcut on error, so will always traverse the whole list/'Traversable' structure.
--
-- This is a useful error handling function in many circumstances,
-- because it won’t only return the first error that happens, but rather all of them.
traverseValidateM :: forall t m a err b. (Traversable t, Applicative m) => (a -> m (Either err b)) -> t a -> m (Either (NonEmpty err) (t b))
traverseValidateM :: forall (t :: Type -> Type) (m :: Type -> Type) a err b.
(Traversable t, Applicative m) =>
(a -> m (Either err b)) -> t a -> m (Either (NonEmpty err) (t b))
traverseValidateM a -> m (Either err b)
f t a
as =
  t a
as
    t a
-> (t a -> m (t (Validation (NonEmpty err) b)))
-> m (t (Validation (NonEmpty err) b))
forall a b. a -> (a -> b) -> b
& forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse @t @m (\a
a -> a
a a -> (a -> m (Either err b)) -> m (Either err b)
forall a b. a -> (a -> b) -> b
& a -> m (Either err b)
f m (Either err b)
-> (Either err b -> Validation (NonEmpty err) b)
-> m (Validation (NonEmpty err) b)
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> Either err b -> Validation (NonEmpty err) b
forall a c. Either a c -> Validation (NonEmpty a) c
eitherToListValidation)
    m (t (Validation (NonEmpty err) b))
-> (t (Validation (NonEmpty err) b)
    -> Validation (NonEmpty err) (t b))
-> m (Validation (NonEmpty err) (t b))
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> forall (t :: Type -> Type) (f :: Type -> Type) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
sequenceA @t @(Validation _)
    m (Validation (NonEmpty err) (t b))
-> (Validation (NonEmpty err) (t b) -> Either (NonEmpty err) (t b))
-> m (Either (NonEmpty err) (t b))
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> Validation (NonEmpty err) (t b) -> Either (NonEmpty err) (t b)
forall e a. Validation e a -> Either e a
validationToEither

-- | 'traverse_' with a function returning 'm Either' and collect all errors that happen, if they happen.
--
-- Does not shortcut on error, so will always traverse the whole list/'Traversable' structure.
--
-- This is a useful error handling function in many circumstances,
-- because it won’t only return the first error that happens, but rather all of them.
traverseValidateM_ :: forall t m a err. (Traversable t, Applicative m) => (a -> m (Either err ())) -> t a -> m (Either (NonEmpty err) ())
traverseValidateM_ :: forall (t :: Type -> Type) (m :: Type -> Type) a err.
(Traversable t, Applicative m) =>
(a -> m (Either err ())) -> t a -> m (Either (NonEmpty err) ())
traverseValidateM_ a -> m (Either err ())
f t a
as =
  t a
as
    t a
-> (t a -> m (t (Validation (NonEmpty err) ())))
-> m (t (Validation (NonEmpty err) ()))
forall a b. a -> (a -> b) -> b
& forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse @t @m (\a
a -> a
a a -> (a -> m (Either err ())) -> m (Either err ())
forall a b. a -> (a -> b) -> b
& a -> m (Either err ())
f m (Either err ())
-> (Either err () -> Validation (NonEmpty err) ())
-> m (Validation (NonEmpty err) ())
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> Either err () -> Validation (NonEmpty err) ()
forall a c. Either a c -> Validation (NonEmpty a) c
eitherToListValidation)
    m (t (Validation (NonEmpty err) ()))
-> (t (Validation (NonEmpty err) ())
    -> Validation (NonEmpty err) ())
-> m (Validation (NonEmpty err) ())
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> forall (t :: Type -> Type) (f :: Type -> Type) a.
(Foldable t, Applicative f) =>
t (f a) -> f ()
sequenceA_ @t @(Validation _)
    m (Validation (NonEmpty err) ())
-> (Validation (NonEmpty err) () -> Either (NonEmpty err) ())
-> m (Either (NonEmpty err) ())
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> Validation (NonEmpty err) () -> Either (NonEmpty err) ()
forall e a. Validation e a -> Either e a
validationToEither

-- | Like 'eitherToValidation', but puts the Error side into a NonEmpty list
-- to make it combine with other validations.
--
-- See also 'validateEithers', if you have a list of Either and want to collect all errors.
eitherToListValidation :: Either a c -> Validation (NonEmpty a) c
eitherToListValidation :: forall a c. Either a c -> Validation (NonEmpty a) c
eitherToListValidation = (a -> NonEmpty a) -> Validation a c -> Validation (NonEmpty a) c
forall a b c. (a -> b) -> Validation a c -> Validation b c
forall (p :: Type -> Type -> Type) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first a -> NonEmpty a
forall a. a -> NonEmpty a
singleton (Validation a c -> Validation (NonEmpty a) c)
-> (Either a c -> Validation a c)
-> Either a c
-> Validation (NonEmpty a) c
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either a c -> Validation a c
forall e a. Either e a -> Validation e a
eitherToValidation

-- | Convert an 'Either' to a 'These'.
eitherToThese :: Either err a -> These err a
eitherToThese :: forall err a. Either err a -> These err a
eitherToThese (Left err
err) = err -> These err a
forall a b. a -> These a b
This err
err
eitherToThese (Right a
a) = a -> These err a
forall a b. b -> These a b
That a
a

-- | Like 'eitherToThese', but puts the Error side into a NonEmpty list
-- to make it combine with other theses.
eitherToListThese :: Either err a -> These (NonEmpty err) a
eitherToListThese :: forall err a. Either err a -> These (NonEmpty err) a
eitherToListThese (Left err
e) = NonEmpty err -> These (NonEmpty err) a
forall a b. a -> These a b
This (err -> NonEmpty err
forall a. a -> NonEmpty a
singleton err
e)
eitherToListThese (Right a
a) = a -> These (NonEmpty err) a
forall a b. b -> These a b
That a
a

-- | Convert a 'Validation' to a 'These'.
validationToThese :: Validation err a -> These err a
validationToThese :: forall err a. Validation err a -> These err a
validationToThese (Failure err
err) = err -> These err a
forall a b. a -> These a b
This err
err
validationToThese (Success a
a) = a -> These err a
forall a b. b -> These a b
That a
a

-- | Nested '>>=' of a These inside some other @m@.
--
-- Use if you want to collect errors and successes, and want to chain multiple function returning 'These'.
thenThese ::
  (Monad m, Semigroup err) =>
  (a -> m (These err b)) ->
  m (These err a) ->
  m (These err b)
thenThese :: forall (m :: Type -> Type) err a b.
(Monad m, Semigroup err) =>
(a -> m (These err b)) -> m (These err a) -> m (These err b)
thenThese a -> m (These err b)
f m (These err a)
x = do
  These err a
th <- m (These err a)
x
  These err (These err b) -> These err b
forall (m :: Type -> Type) a. Monad m => m (m a) -> m a
join (These err (These err b) -> These err b)
-> m (These err (These err b)) -> m (These err b)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> m (These err b))
-> These err a -> m (These err (These err b))
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> These err a -> f (These err b)
traverse a -> m (These err b)
f These err a
th

-- | Nested validating bind-like combinator.
--
-- Use if you want to collect errors, and want to chain multiple functions returning 'Validation'.
thenValidate ::
  (a -> Validation err b) ->
  Validation err a ->
  Validation err b
thenValidate :: forall a err b.
(a -> Validation err b) -> Validation err a -> Validation err b
thenValidate a -> Validation err b
f = \case
  Success a
a -> a -> Validation err b
f a
a
  Failure err
err -> err -> Validation err b
forall e a. e -> Validation e a
Failure err
err

-- | Nested validating bind-like combinator inside some other @m@.
--
-- Use if you want to collect errors, and want to chain multiple functions returning 'Validation'.
thenValidateM ::
  (Monad m) =>
  (a -> m (Validation err b)) ->
  m (Validation err a) ->
  m (Validation err b)
thenValidateM :: forall (m :: Type -> Type) a err b.
Monad m =>
(a -> m (Validation err b))
-> m (Validation err a) -> m (Validation err b)
thenValidateM a -> m (Validation err b)
f m (Validation err a)
x =
  Either err b -> Validation err b
forall e a. Either e a -> Validation e a
eitherToValidation (Either err b -> Validation err b)
-> m (Either err b) -> m (Validation err b)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> do
    Either err a
x' <- Validation err a -> Either err a
forall e a. Validation e a -> Either e a
validationToEither (Validation err a -> Either err a)
-> m (Validation err a) -> m (Either err a)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> m (Validation err a)
x
    case Either err a
x' of
      Left err
err -> Either err b -> m (Either err b)
forall a. a -> m a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (Either err b -> m (Either err b))
-> Either err b -> m (Either err b)
forall a b. (a -> b) -> a -> b
$ err -> Either err b
forall a b. a -> Either a b
Left err
err
      Right a
a -> Validation err b -> Either err b
forall e a. Validation e a -> Either e a
validationToEither (Validation err b -> Either err b)
-> m (Validation err b) -> m (Either err b)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> a -> m (Validation err b)
f a
a

-- | Put the text to @stderr@.
putStderrLn :: Text -> IO ()
putStderrLn :: Text -> IO ()
putStderrLn Text
msg =
  Handle -> String -> IO ()
System.IO.hPutStrLn Handle
System.IO.stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ Text -> String
textToString Text
msg

exitWithMessage :: Text -> IO a
exitWithMessage :: forall a. Text -> IO a
exitWithMessage Text
msg = do
  Text -> IO ()
putStderrLn Text
msg
  ExitCode -> IO a
forall a. ExitCode -> IO a
System.Exit.exitWith (ExitCode -> IO a) -> ExitCode -> IO a
forall a b. (a -> b) -> a -> b
$ Int -> ExitCode
System.Exit.ExitFailure (-Int
1)

-- | Run some function producing applicative over a traversable data structure,
-- then collect the results in a Monoid.
--
-- Very helpful with side-effecting functions returning @(Validation err a)@:
--
-- @
-- let
--   f :: Text -> IO (Validation (NonEmpty Error) Text)
--   f t = pure $ if t == "foo" then Success t else Failure (singleton ("not foo: " <> t))
--
-- in traverseFold f [ "foo", "bar", "baz" ]
--   == Failure ("not foo bar" :| ["not foo baz"])
-- @
--
-- … since @(Semigroup err => Validation err a)@ is a @Semigroup@/@Monoid@ itself.
traverseFold :: (Applicative ap, Traversable t, Monoid m) => (a -> ap m) -> t a -> ap m
{-# INLINE traverseFold #-}
traverseFold :: forall (ap :: Type -> Type) (t :: Type -> Type) m a.
(Applicative ap, Traversable t, Monoid m) =>
(a -> ap m) -> t a -> ap m
traverseFold a -> ap m
f t a
xs =
  -- note: could be weakened to (Foldable t) via `getAp . foldMap (Ap . f)`
  t m -> m
forall m. Monoid m => t m -> m
forall (t :: Type -> Type) m. (Foldable t, Monoid m) => t m -> m
fold (t m -> m) -> ap (t m) -> ap m
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> ap m) -> t a -> ap (t m)
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> t a -> f (t b)
traverse a -> ap m
f t a
xs

-- | Like 'traverseFold', but fold over a semigroup instead of a Monoid, by providing a starting element.
traverseFoldDefault :: (Applicative ap, Traversable t, Semigroup m) => m -> (a -> ap m) -> t a -> ap m
{-# INLINE traverseFoldDefault #-}
traverseFoldDefault :: forall (ap :: Type -> Type) (t :: Type -> Type) m a.
(Applicative ap, Traversable t, Semigroup m) =>
m -> (a -> ap m) -> t a -> ap m
traverseFoldDefault m
def a -> ap m
f t a
xs = m -> t m -> m
foldDef m
def (t m -> m) -> ap (t m) -> ap m
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> ap m) -> t a -> ap (t m)
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> t a -> f (t b)
traverse a -> ap m
f t a
xs
  where
    foldDef :: m -> t m -> m
foldDef = (m -> m -> m) -> m -> t m -> m
forall a b. (a -> b -> b) -> b -> t a -> b
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr m -> m -> m
forall a. Semigroup a => a -> a -> a
(<>)

-- | Same as 'traverseFold', but with a 'Semigroup' and 'Traversable1' restriction.
traverseFold1 :: (Applicative ap, Traversable1 t, Semigroup s) => (a -> ap s) -> t a -> ap s
{-# INLINE traverseFold1 #-}
-- note: cannot be weakened to (Foldable1 t) because there is no `Ap` for Semigroup (No `Apply` typeclass)
traverseFold1 :: forall (ap :: Type -> Type) (t :: Type -> Type) s a.
(Applicative ap, Traversable1 t, Semigroup s) =>
(a -> ap s) -> t a -> ap s
traverseFold1 a -> ap s
f t a
xs = t s -> s
forall m. Semigroup m => t m -> m
forall (t :: Type -> Type) m.
(Foldable1 t, Semigroup m) =>
t m -> m
fold1 (t s -> s) -> ap (t s) -> ap s
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> ap s) -> t a -> ap (t s)
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> t a -> f (t b)
traverse a -> ap s
f t a
xs

-- | Use this in places where the code is still to be implemented.
--
-- It always type-checks and will show a warning at compile time if it was forgotten in the code.
--
-- Use instead of 'error' and 'undefined' for code that hasn’t been written.
--
-- Uses the same trick as https://hackage.haskell.org/package/protolude-0.3.0/docs/src/Protolude.Error.html#error
{-# WARNING todo "'todo' (undefined code) remains in code" #-}
todo :: forall (r :: RuntimeRep). forall (a :: TYPE r). (HasCallStack) => a
todo :: forall a. HasCallStack => a
todo = SomeException -> a
forall a b. a -> b
raise# (String -> CallStack -> SomeException
errorCallWithCallStackException String
"This code was not yet implemented: TODO" HasCallStack
CallStack
?callStack)

-- | Convert an integer to a 'Natural' if possible
--
-- Named the same as the function from "GHC.Natural", but does not crash.
intToNatural :: (Integral a) => a -> Maybe Natural
intToNatural :: forall a. Integral a => a -> Maybe Natural
intToNatural a
i =
  if a
i a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
0
    then Maybe Natural
forall a. Maybe a
Nothing
    else Natural -> Maybe Natural
forall a. a -> Maybe a
Just (Natural -> Maybe Natural) -> Natural -> Maybe Natural
forall a b. (a -> b) -> a -> b
$ a -> Natural
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
i

-- | @inverseFunction f@ creates a function that is the inverse of a given function
-- @f@. It does so by constructing 'M.Map' internally for each value @f a@. The
-- implementation makes sure that the 'M.Map' is constructed only once and then
-- shared for every call.
--
-- __Memory usage note:__ don't inverse functions that have types like 'Int'
-- as their result. In this case the created 'M.Map' will have huge size.
--
-- The complexity of reversed mapping is \(\mathcal{O}(\log n)\).
--
-- __Performance note:__ make sure to specialize monomorphic type of your functions
-- that use 'inverseFunction' to avoid 'M.Map' reconstruction.
--
-- One of the common 'inverseFunction' use-case is inverting the 'show' or a 'show'-like
-- function.
--
-- >>> data Color = Red | Green | Blue deriving (Show, Enum, Bounded)
-- >>> parse = inverseFunction show :: String -> Maybe Color
-- >>> parse "Red"
-- Just Red
-- >>> parse "Black"
-- Nothing
--
-- __Correctness note:__ 'inverseFunction' expects /injective function/ as its argument,
-- i.e. the function must map distinct arguments to distinct values.
--
-- Typical usage of this function looks like this:
--
-- @
-- __data__ GhcVer
--    = Ghc802
--    | Ghc822
--    | Ghc844
--    | Ghc865
--    | Ghc881
--    __deriving__ ('Eq', 'Ord', 'Show', 'Enum', 'Bounded')
--
-- showGhcVer :: GhcVer -> 'Text'
-- showGhcVer = \\__case__
--    Ghc802 -> "8.0.2"
--    Ghc822 -> "8.2.2"
--    Ghc844 -> "8.4.4"
--    Ghc865 -> "8.6.5"
--    Ghc881 -> "8.8.1"
--
-- parseGhcVer :: 'Text' -> 'Maybe' GhcVer
-- parseGhcVer = 'inverseFunction' showGhcVer
--
-- Taken from relude’s @Relude.Extra.Enum@.
inverseFunction ::
  forall a k.
  (Bounded a, Enum a, Ord k) =>
  (a -> k) ->
  (k -> Maybe a)
inverseFunction :: forall a k. (Bounded a, Enum a, Ord k) => (a -> k) -> k -> Maybe a
inverseFunction a -> k
f k
k = k -> Map k a -> Maybe a
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup k
k (Map k a -> Maybe a) -> Map k a -> Maybe a
forall a b. (a -> b) -> a -> b
$ (a -> k) -> Map k a
forall a k. (Bounded a, Enum a, Ord k) => (a -> k) -> Map k a
inverseMap a -> k
f

-- | Like `inverseFunction`, but instead of returning the function
-- it returns a mapping from all possible outputs to their possible inputs.
--
-- This has the same restrictions of 'inverseFunction'.
inverseMap :: forall a k. (Bounded a, Enum a, Ord k) => (a -> k) -> Map k a
inverseMap :: forall a k. (Bounded a, Enum a, Ord k) => (a -> k) -> Map k a
inverseMap a -> k
f = [a]
forall a. (Enum a, Bounded a) => [a]
enumerateAll [a] -> (a -> (k, a)) -> [(k, a)]
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> (\a
a -> (a -> k
f a
a, a
a)) [(k, a)] -> ([(k, a)] -> Map k a) -> Map k a
forall a b. a -> (a -> b) -> b
& [(k, a)] -> Map k a
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList

-- | All possible values in this enum.
enumerateAll :: (Enum a, Bounded a) => [a]
enumerateAll :: forall a. (Enum a, Bounded a) => [a]
enumerateAll = [a
forall a. Bounded a => a
minBound .. a
forall a. Bounded a => a
maxBound]

-- | Create a 'Map' from a list of values, extracting the map key from each value. Like 'Map.fromList'.
--
-- Attention: if the key is not unique, the earliest value with the key will be in the map.
mapFromListOn :: (Ord key) => (a -> key) -> [a] -> Map key a
mapFromListOn :: forall key a. Ord key => (a -> key) -> [a] -> Map key a
mapFromListOn a -> key
f [a]
xs = [a]
xs [a] -> (a -> (key, a)) -> [(key, a)]
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> (\a
x -> (a -> key
f a
x, a
x)) [(key, a)] -> ([(key, a)] -> Map key a) -> Map key a
forall a b. a -> (a -> b) -> b
& [(key, a)] -> Map key a
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList

-- | Create a 'Map' from a list of values, merging multiple values at the same key with '<>' (left-to-right)
--
-- `f` has to extract the key and value. Value must be mergable.
--
-- Attention: if the key is not unique, the earliest value with the key will be in the map.
mapFromListOnMerge :: (Ord key, Semigroup s) => (a -> (key, s)) -> [a] -> Map key s
mapFromListOnMerge :: forall key s a.
(Ord key, Semigroup s) =>
(a -> (key, s)) -> [a] -> Map key s
mapFromListOnMerge a -> (key, s)
f [a]
xs =
  [a]
xs
    [a] -> (a -> (key, s)) -> [(key, s)]
forall (f :: Type -> Type) a b. Functor f => f a -> (a -> b) -> f b
<&> (\a
x -> a -> (key, s)
f a
x)
    [(key, s)] -> ([(key, s)] -> Map key s) -> Map key s
forall a b. a -> (a -> b) -> b
& (s -> s -> s) -> [(key, s)] -> Map key s
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith
      -- we have to flip (`<>`) because `Map.fromListWith` merges its values “the other way around”
      ((s -> s -> s) -> s -> s -> s
forall a b c. (a -> b -> c) -> b -> a -> c
flip s -> s -> s
forall a. Semigroup a => a -> a -> a
(<>))

-- | If the predicate is true, return the @m@, else 'mempty'.
--
-- This can be used (together with `ifExists`) to e.g. create lists with optional elements:
--
-- >>> import Data.Monoid (Sum(..))
--
-- >>> :{ mconcat [
--   ifTrue (1 == 1) [1],
--   [2, 3, 4],
--   ifTrue False [5],
-- ]
-- :}
-- [1,2,3,4]
--
-- Or any other Monoid:
--
-- >>> mconcat [ Sum 1, ifTrue (1 == 1) (Sum 2), Sum 3 ]

-- Sum {getSum = 6}

ifTrue :: (Monoid m) => Bool -> m -> m
ifTrue :: forall m. Monoid m => Bool -> m -> m
ifTrue Bool
pred' m
m = if Bool
pred' then m
m else m
forall a. Monoid a => a
mempty

-- | If the given @Maybe@ is @Just@, return the @m@, else return mempty.

-- This can be used (together with `ifTrue`) to e.g. create lists with optional elements:
--
-- >>> import Data.Monoid (Sum(..))
--
-- >>> :{ mconcat [
--   ifExists (Just [1]),
--   [2, 3, 4],
--   ifExists Nothing,
-- ]
-- :}
-- [1,2,3,4]
--
-- Or any other Monoid:
--
-- >>> mconcat [ Sum 1, ifExists (Just (Sum 2)), Sum 3 ]

-- Sum {getSum = 6}

ifExists :: (Monoid m) => Maybe m -> m
ifExists :: forall m. Monoid m => Maybe m -> m
ifExists = Maybe m -> m
forall m. Monoid m => Maybe m -> m
forall (t :: Type -> Type) m. (Foldable t, Monoid m) => t m -> m
fold