From eb6baac6e7d16e1547505cbcc1210b9268f72b04 Mon Sep 17 00:00:00 2001 From: Simon Michael Date: Mon, 30 Jul 2018 11:04:33 +0100 Subject: [PATCH] lib: make applyN more robust (#852) --- hledger-lib/Hledger/Utils.hs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/hledger-lib/Hledger/Utils.hs b/hledger-lib/Hledger/Utils.hs index 41fb48129..47f49551a 100644 --- a/hledger-lib/Hledger/Utils.hs +++ b/hledger-lib/Hledger/Utils.hs @@ -129,9 +129,12 @@ isLeft _ = False isRight :: Either a b -> Bool isRight = not . isLeft --- | Apply a function the specified number of times. Possibly uses O(n) stack ? +-- | Apply a function the specified number of times, +-- which should be > 0 (otherwise does nothing). +-- Possibly uses O(n) stack ? applyN :: Int -> (a -> a) -> a -> a -applyN n f = (!! n) . iterate f +applyN n f | n < 1 = id + | otherwise = (!! n) . iterate f -- from protolude, compare -- applyN :: Int -> (a -> a) -> a -> a -- applyN n f = X.foldr (.) identity (X.replicate n f) @@ -218,4 +221,4 @@ mapM' f = sequence' . map f tests_Hledger_Utils :: Test tests_Hledger_Utils = TestList [ tests_Hledger_Utils_Text - ] \ No newline at end of file + ]