{- This file is part of feed-collect.
 -
 - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
 - Date parser format strings written originally by koral <koral@mailoo.org>
 - for the imm package and were copied here (imm is released as WTFPL).
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

{-# Language CPP #-}

module Control.Applicative.Util
    ( applyIf
    , applyIf'
    )
where

#if MIN_VERSION_base(4,8,0)

import Control.Applicative

-- | Conditionally apply an applicative action to a value. If the condition is
-- 'False', return the value as-is (inside the applicative).
applyIf :: Applicative f => a -> Bool -> (a -> f a) -> f a
applyIf val apply action = if apply then action val else pure val

-- | Like 'applyIf', but takes a condition predicate to apply to the value.
applyIf' :: Applicative f => a -> (a -> Bool) -> (a -> f a) -> f a
applyIf' v p = applyIf v (p v)

#else

-- | Conditionally apply an monadic action to a value. If the condition is
-- 'False', return the value as-is (inside the monad).
applyIf :: Monad m => a -> Bool -> (a -> m a) -> m a
applyIf val apply action = if apply then action val else return val

-- | Like 'applyIf', but takes a condition predicate to apply to the value.
applyIf' :: Monad m => a -> (a -> Bool) -> (a -> m a) -> m a
applyIf' v p = applyIf v (p v)

#endif