Skip to content

Add takeIterateM #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Tests/test-monad-loops.hs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ testTakeWhileMEdgeCase3 = do
let expected = takeWhile (const undefined) emptyList
actual @?= expected

testTakeIterateM :: Assertion
testTakeIterateM = do
let n = 3 :: Int
actual <- takeIterateM n (return . (+ 1)) 0
expected <- takeIterateM 1 (return . id) n
actual @?= expected

testTakeIterateMEdgeCase1 :: Assertion
testTakeIterateMEdgeCase1 = do
let n = 0 :: Int
actual <- takeIterateM n (return . (+ 1)) 0
expected <- return n
actual @?= expected

tests :: TestTree
tests = testGroup "unit tests"
[ testCase
Expand All @@ -46,7 +60,14 @@ tests = testGroup "unit tests"
, testCase
"Testing `takeWhileM (edge case 3)`"
testTakeWhileMEdgeCase3
, testCase
"Testing `takeIterateM`"
testTakeIterateM
, testCase
"Testing `takeIterateM` (edge case 1)"
testTakeIterateMEdgeCase1
]


main :: IO ()
main = defaultMain tests
main = defaultMain tests
6 changes: 6 additions & 0 deletions src/Control/Monad/Loops.hs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ iterateM_ :: Monad m => (a -> m a) -> a -> m b
iterateM_ f = g
where g x = f x >>= g

{-# SPECIALIZE takeIterateM :: Int -> (a -> IO a) -> a -> IO a #-}
-- |Like 'iterateM_', but only executes the action n times.
takeIterateM :: Monad m => Int -> (a -> m a) -> a -> m a
takeIterateM 0 _ a = return a
takeIterateM n f a = f a >>= takeIterateM (n - 1) f

{-# SPECIALIZE untilM :: IO a -> IO Bool -> IO [a] #-}
{-# SPECIALIZE untilM' :: Monad m => m a -> m Bool -> m [a] #-}
{-# SPECIALIZE untilM' :: IO a -> IO Bool -> IO [a] #-}
Expand Down