-- |
-- Copyright        : (c) Raghu Kaippully, 2020
-- License          : MPL-2.0
-- Maintainer       : rkaippully@gmail.com
--
-- Common utility functions.
module WebGear.Util
  ( takeWhileM
  , splitOn
  , maybeToRight
  ) where

import Data.List.NonEmpty (NonEmpty (..), toList)


takeWhileM :: Monad m => (a -> Bool) -> [m a] -> m [a]
takeWhileM :: (a -> Bool) -> [m a] -> m [a]
takeWhileM a -> Bool
_    []     = [a] -> m [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
takeWhileM a -> Bool
p (m a
mx:[m a]
mxs) = do
  a
x <- m a
mx
  if a -> Bool
p a
x
    then (a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
:) ([a] -> [a]) -> m [a] -> m [a]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> Bool) -> [m a] -> m [a]
forall (m :: * -> *) a. Monad m => (a -> Bool) -> [m a] -> m [a]
takeWhileM a -> Bool
p [m a]
mxs
    else [a] -> m [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []

splitOn :: Eq a => a -> [a] -> NonEmpty [a]
splitOn :: a -> [a] -> NonEmpty [a]
splitOn a
sep = (a -> NonEmpty [a] -> NonEmpty [a])
-> NonEmpty [a] -> [a] -> NonEmpty [a]
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr a -> NonEmpty [a] -> NonEmpty [a]
f ([] [a] -> [[a]] -> NonEmpty [a]
forall a. a -> [a] -> NonEmpty a
:| [])
  where
    f :: a -> NonEmpty [a] -> NonEmpty [a]
f a
x NonEmpty [a]
acc       | a
x a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
sep = [] [a] -> [[a]] -> NonEmpty [a]
forall a. a -> [a] -> NonEmpty a
:| NonEmpty [a] -> [[a]]
forall a. NonEmpty a -> [a]
toList NonEmpty [a]
acc
    f a
x ([a]
y :| [[a]]
ys) = (a
xa -> [a] -> [a]
forall a. a -> [a] -> [a]
:[a]
y) [a] -> [[a]] -> NonEmpty [a]
forall a. a -> [a] -> NonEmpty a
:| [[a]]
ys

maybeToRight :: a -> Maybe b -> Either a b
maybeToRight :: a -> Maybe b -> Either a b
maybeToRight a
_ (Just b
x) = b -> Either a b
forall a b. b -> Either a b
Right b
x
maybeToRight a
y Maybe b
Nothing  = a -> Either a b
forall a b. a -> Either a b
Left a
y