Skip to content

Commit

Permalink
Merge pull request #156 from matthewleon/Function.applyN
Browse files Browse the repository at this point in the history
Function.applyN
  • Loading branch information
garyb authored Apr 13, 2018
2 parents 808fb9d + 3cb1fd9 commit 3cbf8d3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
18 changes: 18 additions & 0 deletions src/Data/Function.purs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ module Data.Function
, const
, apply, ($)
, applyFlipped, (#)
, applyN
, on
, module Control.Category
) where

import Control.Category (id, compose, (<<<), (>>>))
import Data.Boolean (otherwise)
import Data.Ord ((<=))
import Data.Ring ((-))

-- | Flips the order of the arguments to a function of two arguments.
-- |
Expand Down Expand Up @@ -77,6 +81,20 @@ applyFlipped x f = f x
-- | ```
infixl 1 applyFlipped as #

-- | `applyN f n` applies the function `f` to its argument `n` times.
-- |
-- | If n is less than or equal to 0, the function is not applied.
-- |
-- | ```purescript
-- | applyN (_ + 1) 10 0 == 10
-- | ```
applyN :: forall a. (a -> a) -> Int -> a -> a
applyN f = go
where
go n acc
| n <= 0 = acc
| otherwise = go (n - 1) (f acc)

-- | The `on` function is used to change the domain of a binary operator.
-- |
-- | For example, we can create a function which compares two records based on the values of their `x` properties:
Expand Down
3 changes: 1 addition & 2 deletions src/Data/Ord.purs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ module Data.Ord
) where

import Data.Eq (class Eq, class Eq1)
import Data.Function (on)
import Data.Ord.Unsafe (unsafeCompare)
import Data.Ordering (Ordering(..))
import Data.Ring (class Ring, zero, one, negate)
Expand Down Expand Up @@ -105,7 +104,7 @@ infixl 4 greaterThanOrEq as >=

-- | Compares two values by mapping them to a type with an `Ord` instance.
comparing :: forall a b. Ord b => (a -> b) -> (a -> a -> Ordering)
comparing f = compare `on` f
comparing f x y = compare (f x) (f y)

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

0 comments on commit 3cbf8d3

Please sign in to comment.