state monad implementation