{- |
Taken from Haskore.
-}

module Sound.MIDI.Parser
   (T, zeroOrMore, oneOrMore, StateT(..), force) where

import Control.Monad.State (StateT(StateT, runStateT), liftM2, mplus)
import Control.Monad.Error ()

type T s a = StateT s (Either String) a

{- |
Wadler's force function

'force' guarantees that the parser does not fail.
Thus it makes parsing more lazy.
However if the original parser fails though,
then we get an unrecoverable /irrefutable pattern/ error on 'Just'.
-}
force        :: T s a -> T s a
force p =
   StateT $ \ s ->
     let Right x = runStateT p s
     in  Right x

zeroOrMore   :: T s a -> T s [a]
zeroOrMore p = force $ oneOrMore p `mplus` return []

oneOrMore    :: T s a -> T s [a]
oneOrMore p = liftM2 (:) p (zeroOrMore p)