add pmaybe and pmaybeData utils

This commit is contained in:
Hongrui Fang 2022-07-25 17:59:43 +08:00
parent d858799588
commit 7c36cd95ae
No known key found for this signature in database
GPG key ID: 1E0454204FC7D755

View file

@ -24,6 +24,8 @@ module Agora.Utils (
pltAsData, pltAsData,
pon, pon,
withBuiltinPairAsData, withBuiltinPairAsData,
pmaybeData,
pmaybe,
) where ) where
import Plutarch.Api.V1 ( import Plutarch.Api.V1 (
@ -240,3 +242,30 @@ withBuiltinPairAsData f p =
let a = pfromData $ pfstBuiltin # p let a = pfromData $ pfstBuiltin # p
b = pfromData $ psndBuiltin # p b = pfromData $ psndBuiltin # p
in f a b in f a b
{- | Plutarch version of 'Data.Maybe.maybe'. Take a default value and a function
@f@. If the given 'PMaybe' value is @'PJust' x@, apply the function @f@ to
@x@, otherewise the default value will be retuned.
@since 0.2.0
-}
pmaybe ::
forall (a :: PType) (b :: PType) (s :: S).
Term s (b :--> (a :--> b) :--> PMaybe a :--> b)
pmaybe = phoistAcyclic $
plam $ \n f m -> pmatch m $ \case
PJust x -> f # x
_ -> n
{- | Special version of 'pmaybe' that works with 'PMaybedata'.
@since 0.2.0
-}
pmaybeData ::
forall (a :: PType) (b :: PType) (s :: S).
PIsData a =>
Term s (b :--> (a :--> b) :--> PMaybeData a :--> b)
pmaybeData = phoistAcyclic $
plam $ \n f m -> pmatch m $ \case
PDJust ((pfield @"_0" #) -> x) -> f # x
_ -> n