Skip to content

Commit 42538d7

Browse files
committed
Function.applyN
addresses #155
1 parent 5cade66 commit 42538d7

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/Data/Function.purs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ module Data.Function
88
) where
99

1010
import Control.Category (id, compose, (<<<), (>>>))
11+
import Data.Boolean (otherwise)
12+
import Data.Ord ((<=))
13+
import Data.Ring ((-))
1114

1215
-- | Flips the order of the arguments to a function of two arguments.
1316
-- |
@@ -87,3 +90,13 @@ infixl 1 applyFlipped as #
8790
-- | ```
8891
on :: forall a b c. (b -> b -> c) -> (a -> b) -> a -> a -> c
8992
on f g x y = g x `f` g y
93+
94+
-- | Applies a function to an argument `n` times.
95+
-- |
96+
-- | If n is less than or equal to 0, the function is not applied.
97+
applyN :: forall a. (a -> a) -> Int -> a -> a
98+
applyN f n = go n
99+
where
100+
go n' acc
101+
| n' <= 0 = acc
102+
| otherwise = go (n' - 1) $ f acc

src/Data/Ord.purs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ module Data.Ord
1515
) where
1616

1717
import Data.Eq (class Eq, class Eq1)
18-
import Data.Function (on)
1918
import Data.Ord.Unsafe (unsafeCompare)
2019
import Data.Ordering (Ordering(..))
2120
import Data.Ring (class Ring, zero, one, negate)
@@ -106,6 +105,9 @@ infixl 4 greaterThanOrEq as >=
106105
-- | Compares two values by mapping them to a type with an `Ord` instance.
107106
comparing :: forall a b. Ord b => (a -> b) -> (a -> a -> Ordering)
108107
comparing f = compare `on` f
108+
where
109+
-- we need to redefine this to avoid a dependency cycle with `Data.Function`
110+
on f g x y = g x `f` g y
109111

110112
-- | Take the minimum of two values. If they are considered equal, the first
111113
-- | argument is chosen.

0 commit comments

Comments
 (0)