Skip to content

Commit 3cbf8d3

Browse files
authored
Merge pull request #156 from matthewleon/Function.applyN
Function.applyN
2 parents 808fb9d + 3cb1fd9 commit 3cbf8d3

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/Data/Function.purs

+18
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@ module Data.Function
33
, const
44
, apply, ($)
55
, applyFlipped, (#)
6+
, applyN
67
, on
78
, module Control.Category
89
) where
910

1011
import Control.Category (id, compose, (<<<), (>>>))
12+
import Data.Boolean (otherwise)
13+
import Data.Ord ((<=))
14+
import Data.Ring ((-))
1115

1216
-- | Flips the order of the arguments to a function of two arguments.
1317
-- |
@@ -77,6 +81,20 @@ applyFlipped x f = f x
7781
-- | ```
7882
infixl 1 applyFlipped as #
7983

84+
-- | `applyN f n` applies the function `f` to its argument `n` times.
85+
-- |
86+
-- | If n is less than or equal to 0, the function is not applied.
87+
-- |
88+
-- | ```purescript
89+
-- | applyN (_ + 1) 10 0 == 10
90+
-- | ```
91+
applyN :: forall a. (a -> a) -> Int -> a -> a
92+
applyN f = go
93+
where
94+
go n acc
95+
| n <= 0 = acc
96+
| otherwise = go (n - 1) (f acc)
97+
8098
-- | The `on` function is used to change the domain of a binary operator.
8199
-- |
82100
-- | For example, we can create a function which compares two records based on the values of their `x` properties:

src/Data/Ord.purs

+1-2
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)
@@ -105,7 +104,7 @@ infixl 4 greaterThanOrEq as >=
105104

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)
108-
comparing f = compare `on` f
107+
comparing f x y = compare (f x) (f y)
109108

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

0 commit comments

Comments
 (0)