From 3cb1fd9bc14cebcec1db9766868faf19d491a3b2 Mon Sep 17 00:00:00 2001 From: Matthew Leon Date: Sat, 27 Jan 2018 11:40:47 -0500 Subject: [PATCH] Function.applyN addresses https://github.com/purescript/purescript-prelude/issues/155 --- src/Data/Function.purs | 18 ++++++++++++++++++ src/Data/Ord.purs | 3 +-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Data/Function.purs b/src/Data/Function.purs index f3f067d9..e4875d97 100644 --- a/src/Data/Function.purs +++ b/src/Data/Function.purs @@ -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. -- | @@ -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: diff --git a/src/Data/Ord.purs b/src/Data/Ord.purs index 0b5ca7b0..a3bec35f 100644 --- a/src/Data/Ord.purs +++ b/src/Data/Ord.purs @@ -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) @@ -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.