{-# OPTIONS_GHC -fno-omit-interface-pragmas #-}
module PlutusTx.Maybe (Maybe(..), isJust, isNothing, maybe, fromMaybe, mapMaybe) where

{-
We export off-chain Haskell's Maybe type as on-chain Plutus's Maybe type since they are the same.
-}

import PlutusTx.Base (id)
import PlutusTx.Bool
import PlutusTx.List (foldr)
import Prelude (Maybe (..))

{- HLINT ignore -}

-- | Check if a 'Maybe' @a@ is @Just a@
--
--   >>> isJust Nothing
--   False
--   >>> isJust (Just "plutus")
--   True
--
isJust :: Maybe a -> Bool
isJust :: forall a. Maybe a -> Bool
isJust Maybe a
m = case Maybe a
m of { Just a
_ -> Bool
True; Maybe a
_ -> Bool
False; }
{-# INLINABLE isJust #-}

-- | Check if a 'Maybe' @a@ is @Nothing@
--
--   >>> isNothing Nothing
--   True
--   >>> isNothing (Just "plutus")
--   False
--
isNothing :: Maybe a -> Bool
isNothing :: forall a. Maybe a -> Bool
isNothing Maybe a
m = case Maybe a
m of { Just a
_ -> Bool
False; Maybe a
_ -> Bool
True; }
{-# INLINABLE isNothing #-}

-- | Plutus Tx version of 'Prelude.maybe'.
--
--   >>> maybe "platypus" (\s -> s) (Just "plutus")
--   "plutus"
--   >>> maybe "platypus" (\s -> s) Nothing
--   "platypus"
--
maybe :: b -> (a -> b) -> Maybe a -> b
maybe :: forall b a. b -> (a -> b) -> Maybe a -> b
maybe b
b a -> b
f Maybe a
m = case Maybe a
m of
    Maybe a
Nothing -> b
b
    Just a
a  -> a -> b
f a
a
{-# INLINABLE maybe #-}

-- | Plutus Tx version of 'Data.Maybe.fromMaybe'
fromMaybe :: a -> Maybe a -> a
fromMaybe :: forall a. a -> Maybe a -> a
fromMaybe a
a = a -> (a -> a) -> Maybe a -> a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe a
a a -> a
forall a. a -> a
id
{-# INLINABLE fromMaybe #-}

-- | Plutus Tx version of 'Data.Maybe.mapMaybe'.
--
--   >>> mapMaybe (\i -> if i == 2 then Just '2' else Nothing) [1, 2, 3, 4]
--   "2"
--
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe :: forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe a -> Maybe b
p = (a -> [b] -> [b]) -> [b] -> [a] -> [b]
forall a b. (a -> b -> b) -> b -> [a] -> b
foldr (\a
e [b]
xs -> [b] -> (b -> [b]) -> Maybe b -> [b]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [b]
xs (b -> [b] -> [b]
forall a. a -> [a] -> [a]
:[b]
xs) (a -> Maybe b
p a
e)) []
{-# INLINABLE mapMaybe #-}