-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A numeric class hierarchy. -- -- This package provides alternative numeric classes over Prelude. -- -- The numeric class constellation looks somewhat like: -- -- --
-- >>> {-# LANGUAGE GHC2021 #-}
--
-- >>> {-# LANGUAGE RebindableSyntax #-}
--
-- >>> import NumHask.Prelude
--
--
-- See NumHask for a detailed overview.
@package numhask
@version 0.12.0.3
-- | Additive classes
module NumHask.Algebra.Additive
-- | or Addition
--
-- For practical reasons, we begin the class tree with Additive.
-- Starting with Associative and Unital, or using
-- Semigroup and Monoid from base tends to confuse the
-- interface once you start having to disinguish between (say) monoidal
-- addition and monoidal multiplication.
--
-- -- \a -> zero + a == a ---- --
-- \a -> a + zero == a ---- --
-- \a b c -> (a + b) + c == a + (b + c) ---- --
-- \a b -> a + b == b + a ---- -- By convention, (+) is regarded as commutative, but this is not -- universal, and the introduction of another symbol which means -- non-commutative addition seems a bit dogmatic. -- --
-- >>> zero + 1 -- 1 ---- --
-- >>> 1 + 1 -- 2 --class Additive a (+) :: Additive a => a -> a -> a zero :: Additive a => a infixl 6 + -- | A wrapper for an Additive which distinguishes the additive structure newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Compute the sum of a Foldable. -- --
-- >>> sum [0..10] -- 55 --sum :: (Additive a, Foldable f) => f a -> a -- | Compute the accumulating sum of a Traversable. -- --
-- >>> accsum [0..10] -- [0,1,3,6,10,15,21,28,36,45,55] --accsum :: (Additive a, Traversable f) => f a -> f a -- | or Subtraction -- --
-- \a -> a - a == zero ---- --
-- \a -> negate a == zero - a ---- --
-- \a -> negate a + a == zero ---- --
-- \a -> a + negate a == zero ---- --
-- >>> negate 1 -- -1 ---- --
-- >>> 1 - 2 -- -1 --class (Additive a) => Subtractive a negate :: Subtractive a => a -> a (-) :: Subtractive a => a -> a -> a infixl 6 - instance GHC.Show.Show a => GHC.Show.Show (NumHask.Algebra.Additive.Sum a) instance GHC.Classes.Ord a => GHC.Classes.Ord (NumHask.Algebra.Additive.Sum a) instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Algebra.Additive.Sum a) instance NumHask.Algebra.Additive.Additive a => NumHask.Algebra.Additive.Additive (NumHask.Algebra.Additive.Sum a) instance NumHask.Algebra.Additive.Subtractive GHC.Types.Double instance NumHask.Algebra.Additive.Subtractive GHC.Types.Float instance NumHask.Algebra.Additive.Subtractive GHC.Types.Int instance NumHask.Algebra.Additive.Subtractive GHC.Num.Integer.Integer instance NumHask.Algebra.Additive.Subtractive GHC.Num.Natural.Natural instance NumHask.Algebra.Additive.Subtractive GHC.Int.Int8 instance NumHask.Algebra.Additive.Subtractive GHC.Int.Int16 instance NumHask.Algebra.Additive.Subtractive GHC.Int.Int32 instance NumHask.Algebra.Additive.Subtractive GHC.Int.Int64 instance NumHask.Algebra.Additive.Subtractive GHC.Types.Word instance NumHask.Algebra.Additive.Subtractive GHC.Word.Word8 instance NumHask.Algebra.Additive.Subtractive GHC.Word.Word16 instance NumHask.Algebra.Additive.Subtractive GHC.Word.Word32 instance NumHask.Algebra.Additive.Subtractive GHC.Word.Word64 instance NumHask.Algebra.Additive.Subtractive b => NumHask.Algebra.Additive.Subtractive (a -> b) instance NumHask.Algebra.Additive.Additive a => GHC.Base.Semigroup (NumHask.Algebra.Additive.Sum a) instance NumHask.Algebra.Additive.Additive a => GHC.Base.Monoid (NumHask.Algebra.Additive.Sum a) instance NumHask.Algebra.Additive.Additive GHC.Types.Double instance NumHask.Algebra.Additive.Additive GHC.Types.Float instance NumHask.Algebra.Additive.Additive GHC.Types.Int instance NumHask.Algebra.Additive.Additive GHC.Num.Integer.Integer instance NumHask.Algebra.Additive.Additive GHC.Types.Bool instance NumHask.Algebra.Additive.Additive GHC.Num.Natural.Natural instance NumHask.Algebra.Additive.Additive GHC.Int.Int8 instance NumHask.Algebra.Additive.Additive GHC.Int.Int16 instance NumHask.Algebra.Additive.Additive GHC.Int.Int32 instance NumHask.Algebra.Additive.Additive GHC.Int.Int64 instance NumHask.Algebra.Additive.Additive GHC.Types.Word instance NumHask.Algebra.Additive.Additive GHC.Word.Word8 instance NumHask.Algebra.Additive.Additive GHC.Word.Word16 instance NumHask.Algebra.Additive.Additive GHC.Word.Word32 instance NumHask.Algebra.Additive.Additive GHC.Word.Word64 instance NumHask.Algebra.Additive.Additive b => NumHask.Algebra.Additive.Additive (a -> b) -- | The Group hierarchy module NumHask.Algebra.Group -- | A Magma is a tuple (T,magma) consisting of -- --
-- ∀ a, b ∈ T: a ⊕ b ∈ T ---- -- These laws are true by construction in haskell: the type signature of -- ⊕ and the above mathematical laws are synonyms. class Magma a (⊕) :: Magma a => a -> a -> a infix 3 ⊕ -- | A Unital Magma is a magma with an identity element (the unit). -- --
-- unit ⊕ a = a -- a ⊕ unit = a --class (Magma a) => Unital a unit :: Unital a => a -- | An Associative Magma -- --
-- (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c) --class (Magma a) => Associative a -- | A Commutative Magma is a Magma where the binary operation is -- commutative. -- --
-- a ⊕ b = b ⊕ a --class (Magma a) => Commutative a -- | An Absorbing is a Magma with an Absorbing Element -- --
-- a ⊕ absorb = absorb --class (Magma a) => Absorbing a absorb :: Absorbing a => a -- | An Invertible Magma -- --
-- ∀ a,b ∈ T: inv a ⊕ (a ⊕ b) = b = (b ⊕ a) ⊕ inv a --class (Magma a) => Invertible a inv :: Invertible a => a -> a -- | An Idempotent Magma is a magma where every element is -- Idempotent. -- --
-- a ⊕ a = a --class (Magma a) => Idempotent a -- | A Group is a Associative, Unital and Invertible Magma. type Group a = (Associative a, Unital a, Invertible a) -- | An Abelian Group is an Associative, Unital, Invertible and -- Commutative Magma . In other words, it is a Commutative Group type AbelianGroup a = (Associative a, Unital a, Invertible a, Commutative a) instance NumHask.Algebra.Group.Idempotent b => NumHask.Algebra.Group.Idempotent (a -> b) instance NumHask.Algebra.Group.Absorbing b => NumHask.Algebra.Group.Absorbing (a -> b) instance NumHask.Algebra.Group.Invertible b => NumHask.Algebra.Group.Invertible (a -> b) instance NumHask.Algebra.Group.Commutative b => NumHask.Algebra.Group.Commutative (a -> b) instance NumHask.Algebra.Group.Associative b => NumHask.Algebra.Group.Associative (a -> b) instance NumHask.Algebra.Group.Unital b => NumHask.Algebra.Group.Unital (a -> b) instance NumHask.Algebra.Group.Magma b => NumHask.Algebra.Group.Magma (a -> b) -- | Multiplicative classes module NumHask.Algebra.Multiplicative -- | or Multiplication -- -- For practical reasons, we begin the class tree with Additive -- and Multiplicative. Starting with Associative and -- Unital, or using Semigroup and Monoid from base -- tends to confuse the interface once you start having to disinguish -- between (say) monoidal addition and monoidal multiplication. -- --
-- \a -> one * a == a ---- --
-- \a -> a * one == a ---- --
-- \a b c -> (a * b) * c == a * (b * c) ---- -- By convention, (*) is regarded as not necessarily commutative, but -- this is not universal, and the introduction of another symbol which -- means commutative multiplication seems a bit dogmatic. -- --
-- >>> one * 2 -- 2 ---- --
-- >>> 2 * 3 -- 6 --class Multiplicative a (*) :: Multiplicative a => a -> a -> a one :: Multiplicative a => a infixl 7 * -- | A wrapper for an Multiplicative which distinguishes the multiplicative -- structure newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Compute the product of a Foldable. -- --
-- >>> product [1..5] -- 120 --product :: (Multiplicative a, Foldable f) => f a -> a -- | Compute the accumulating product of a Traversable. -- --
-- >>> accproduct [1..5] -- [1,2,6,24,120] --accproduct :: (Multiplicative a, Traversable f) => f a -> f a -- | or Division -- -- Though unusual, the term Divisive usefully fits in with the grammer of -- other classes and avoids name clashes that occur with some popular -- libraries. -- --
-- \(a :: Double) -> a / a ~= one || a == zero ---- --
-- \(a :: Double) -> recip a ~= one / a || a == zero ---- --
-- \(a :: Double) -> recip a * a ~= one || a == zero ---- --
-- \(a :: Double) -> a * recip a ~= one || a == zero ---- --
-- >>> recip 2.0 -- 0.5 ---- --
-- >>> 1 / 2 -- 0.5 --class (Multiplicative a) => Divisive a recip :: Divisive a => a -> a (/) :: Divisive a => a -> a -> a infixl 7 / instance GHC.Show.Show a => GHC.Show.Show (NumHask.Algebra.Multiplicative.Product a) instance GHC.Classes.Ord a => GHC.Classes.Ord (NumHask.Algebra.Multiplicative.Product a) instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Algebra.Multiplicative.Product a) instance NumHask.Algebra.Multiplicative.Divisive GHC.Types.Double instance NumHask.Algebra.Multiplicative.Divisive GHC.Types.Float instance NumHask.Algebra.Multiplicative.Divisive b => NumHask.Algebra.Multiplicative.Divisive (a -> b) instance NumHask.Algebra.Multiplicative.Multiplicative a => GHC.Base.Semigroup (NumHask.Algebra.Multiplicative.Product a) instance NumHask.Algebra.Multiplicative.Multiplicative a => GHC.Base.Monoid (NumHask.Algebra.Multiplicative.Product a) instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Types.Double instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Types.Float instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Types.Int instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Num.Integer.Integer instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Types.Bool instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Num.Natural.Natural instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Int.Int8 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Int.Int16 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Int.Int32 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Int.Int64 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Types.Word instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Word.Word8 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Word.Word16 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Word.Word32 instance NumHask.Algebra.Multiplicative.Multiplicative GHC.Word.Word64 instance NumHask.Algebra.Multiplicative.Multiplicative b => NumHask.Algebra.Multiplicative.Multiplicative (a -> b) -- | Ring classes module NumHask.Algebra.Ring -- | Distributive -- --
-- \a b c -> a * (b + c) == a * b + a * c ---- --
-- \a b c -> (a + b) * c == a * c + b * c ---- --
-- \a -> zero * a == zero ---- --
-- \a -> a * zero == zero ---- -- The sneaking in of the Absorption laws here glosses over the -- possibility that the multiplicative zero element does not have to -- correspond with the additive unital zero. type Distributive a = (Additive a, Multiplicative a) -- | A Ring is an abelian group under addition (Unital, -- Associative, Commutative, Invertible) and -- monoidal under multiplication (Unital, Associative), and -- where multiplication distributes over addition. -- --
-- \a -> zero + a == a -- \a -> a + zero == a -- \a b c -> (a + b) + c == a + (b + c) -- \a b -> a + b == b + a -- \a -> a - a == zero -- \a -> negate a == zero - a -- \a -> negate a + a == zero -- \a -> a + negate a == zero -- \a -> one * a == a -- \a -> a * one == a -- \a b c -> (a * b) * c == a * (b * c) -- \a b c -> a * (b + c) == a * b + a * c -- \a b c -> (a + b) * c == a * c + b * c -- \a -> zero * a == zero -- \a -> a * zero == zero --type Ring a = (Distributive a, Subtractive a) -- | A StarSemiring is a semiring with an additional unary operator -- (star) satisfying: -- --
-- \a -> star a == one + a * star a --class (Distributive a) => StarSemiring a star :: StarSemiring a => a -> a plus :: StarSemiring a => a -> a -- | A Kleene Algebra is a Star Semiring with idempotent addition. -- --
-- a * x + x = a ==> star a * x + x = x -- x * a + x = a ==> x * star a + x = x --class (StarSemiring a, Idempotent a) => KleeneAlgebra a -- | Involutive Ring -- --
-- adj (a + b) ==> adj a + adj b -- adj (a * b) ==> adj a * adj b -- adj one ==> one -- adj (adj a) ==> a ---- -- Note: elements for which adj a == a are called -- "self-adjoint". class (Distributive a) => InvolutiveRing a adj :: InvolutiveRing a => a -> a -- | Defining two requires adding the multiplicative unital to -- itself. In other words, the concept of two is a Ring one. -- --
-- >>> two -- 2 --two :: (Multiplicative a, Additive a) => a instance NumHask.Algebra.Ring.InvolutiveRing GHC.Types.Double instance NumHask.Algebra.Ring.InvolutiveRing GHC.Types.Float instance NumHask.Algebra.Ring.InvolutiveRing GHC.Num.Integer.Integer instance NumHask.Algebra.Ring.InvolutiveRing GHC.Types.Int instance NumHask.Algebra.Ring.InvolutiveRing GHC.Num.Natural.Natural instance NumHask.Algebra.Ring.InvolutiveRing GHC.Int.Int8 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Int.Int16 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Int.Int32 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Int.Int64 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Types.Word instance NumHask.Algebra.Ring.InvolutiveRing GHC.Word.Word8 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Word.Word16 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Word.Word32 instance NumHask.Algebra.Ring.InvolutiveRing GHC.Word.Word64 -- | Algebra for Actions -- -- Convention: the |'s in the operators point towards the higher-kinded -- number, representing an operator or action into a structure. module NumHask.Algebra.Action -- | Additive Action -- --
-- m |+ zero == m --class (Additive (AdditiveScalar m)) => AdditiveAction m where { type AdditiveScalar m :: Type; } (|+) :: AdditiveAction m => m -> AdditiveScalar m -> m infixl 6 |+ -- | flipped additive action -- --
-- (+|) == flip (|+) -- zero +| m = m --(+|) :: AdditiveAction m => AdditiveScalar m -> m -> m infixl 6 +| -- | Subtractive Action -- --
-- m |- zero = m --class (AdditiveAction m, Subtractive (AdditiveScalar m)) => SubtractiveAction m (|-) :: SubtractiveAction m => m -> AdditiveScalar m -> m infixl 6 |- -- | Subtraction with the scalar on the left -- --
-- (-|) == (+|) . negate -- zero -| m = negate m --(-|) :: (AdditiveAction m, Subtractive m) => AdditiveScalar m -> m -> m infixl 6 -| -- | Multiplicative Action -- --
-- m |* one = m -- m |* zero = zero --class (Multiplicative (Scalar m)) => MultiplicativeAction m where { type Scalar m :: Type; } (|*) :: MultiplicativeAction m => m -> Scalar m -> m infixl 7 |* -- | flipped multiplicative action -- --
-- (*|) == flip (|*) -- one *| m = one -- zero *| m = zero --(*|) :: MultiplicativeAction m => Scalar m -> m -> m infixl 7 *| -- | Divisive Action -- --
-- m |/ one = m --class (Divisive (Scalar m), MultiplicativeAction m) => DivisiveAction m (|/) :: DivisiveAction m => m -> Scalar m -> m infixl 7 |/ -- | left scalar division -- --
-- (/|) == (*|) . recip -- one |/ m = recip m --(/|) :: (MultiplicativeAction m, Divisive m) => Scalar m -> m -> m -- | A Module -- --
-- a *| one == a -- (a + b) *| c == (a *| c) + (b *| c) -- c |* (a + b) == (c |* a) + (c |* b) -- a *| zero == zero -- a *| b == b |* a --type Module m = (Distributive (Scalar m), MultiplicativeAction m) -- | Integral classes module NumHask.Data.Integral -- | An Integral is anything that satisfies the law: -- --
-- \a b -> b == zero || b * (a `div` b) + (a `mod` b) == a ---- --
-- >>> 3 `divMod` 2 -- (1,1) ---- --
-- >>> (-3) `divMod` 2 -- (-2,1) ---- --
-- >>> (-3) `quotRem` 2 -- (-1,-1) --class (Distributive a) => Integral a div :: Integral a => a -> a -> a mod :: Integral a => a -> a -> a divMod :: Integral a => a -> a -> (a, a) quot :: Integral a => a -> a -> a rem :: Integral a => a -> a -> a quotRem :: Integral a => a -> a -> (a, a) infixl 7 `div` infixl 7 `mod` -- | toIntegral is kept separate from Integral to help with compatability -- issues. -- --
-- toIntegral a == a --class ToIntegral a b toIntegral :: ToIntegral a b => a -> b -- | Convert to an Int type ToInt a = ToIntegral a Int -- | Polymorphic version of fromInteger -- --
-- fromIntegral a == a --class FromIntegral a b fromIntegral :: FromIntegral a b => b -> a -- | Convert from an Int type FromInt a = FromIntegral a Int -- | fromInteger is special in two ways: -- --
-- >>> even 2 -- True --even :: (Eq a, Integral a) => a -> Bool -- |
-- >>> odd 3 -- True --odd :: (Eq a, Integral a) => a -> Bool -- | raise a number to an Integral power -- --
-- >>> 2 ^^ 3 -- 8.0 ---- --
-- >>> 2 ^^ (-2) -- 0.25 --(^^) :: (Ord b, Divisive a, Subtractive b, Integral b) => a -> b -> a infixr 8 ^^ -- | raise a number to an Int power -- -- Note: This differs from (^) found in prelude which is a partial -- function (it errors on negative integrals). This is a monomorphic -- version of (^^) provided to help reduce ambiguous type noise in -- common usages. -- --
-- >>> 2 ^ 3 -- 8.0 ---- --
-- >>> 2 ^ (-2) -- 0.25 --(^) :: Divisive a => a -> Int -> a infixr 8 ^ instance NumHask.Data.Integral.FromInteger GHC.Types.Double instance NumHask.Data.Integral.FromInteger GHC.Types.Float instance NumHask.Data.Integral.FromInteger GHC.Types.Int instance NumHask.Data.Integral.FromInteger GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromInteger GHC.Num.Natural.Natural instance NumHask.Data.Integral.FromInteger GHC.Int.Int8 instance NumHask.Data.Integral.FromInteger GHC.Int.Int16 instance NumHask.Data.Integral.FromInteger GHC.Int.Int32 instance NumHask.Data.Integral.FromInteger GHC.Int.Int64 instance NumHask.Data.Integral.FromInteger GHC.Types.Word instance NumHask.Data.Integral.FromInteger GHC.Word.Word8 instance NumHask.Data.Integral.FromInteger GHC.Word.Word16 instance NumHask.Data.Integral.FromInteger GHC.Word.Word32 instance NumHask.Data.Integral.FromInteger GHC.Word.Word64 instance NumHask.Data.Integral.FromIntegral a b => NumHask.Data.Integral.FromIntegral (c -> a) b instance NumHask.Data.Integral.FromIntegral GHC.Types.Double GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Types.Float GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Types.Int GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Num.Integer.Integer GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Num.Natural.Natural GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Int.Int8 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Int.Int16 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Int.Int32 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Int.Int64 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Types.Word GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Word.Word8 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Word.Word16 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Word.Word32 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Word.Word64 GHC.Num.Integer.Integer instance NumHask.Data.Integral.FromIntegral GHC.Types.Double GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Types.Float GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Types.Int GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Num.Integer.Integer GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Num.Natural.Natural GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Int.Int8 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Int.Int16 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Int.Int32 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Int.Int64 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Types.Word GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Word.Word8 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Word.Word16 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Word.Word32 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Word.Word64 GHC.Types.Int instance NumHask.Data.Integral.FromIntegral GHC.Num.Natural.Natural GHC.Num.Natural.Natural instance NumHask.Data.Integral.FromIntegral GHC.Int.Int8 GHC.Int.Int8 instance NumHask.Data.Integral.FromIntegral GHC.Int.Int16 GHC.Int.Int16 instance NumHask.Data.Integral.FromIntegral GHC.Int.Int32 GHC.Int.Int32 instance NumHask.Data.Integral.FromIntegral GHC.Int.Int64 GHC.Int.Int64 instance NumHask.Data.Integral.FromIntegral GHC.Types.Word GHC.Types.Word instance NumHask.Data.Integral.FromIntegral GHC.Word.Word8 GHC.Word.Word8 instance NumHask.Data.Integral.FromIntegral GHC.Word.Word16 GHC.Word.Word16 instance NumHask.Data.Integral.FromIntegral GHC.Word.Word32 GHC.Word.Word32 instance NumHask.Data.Integral.FromIntegral GHC.Word.Word64 GHC.Word.Word64 instance NumHask.Data.Integral.ToIntegral GHC.Num.Integer.Integer GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Types.Int GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Num.Natural.Natural GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Int.Int8 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Int.Int16 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Int.Int32 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Int.Int64 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Types.Word GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Word.Word8 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Word.Word16 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Word.Word32 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Word.Word64 GHC.Num.Integer.Integer instance NumHask.Data.Integral.ToIntegral GHC.Types.Int GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Num.Integer.Integer GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Num.Natural.Natural GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Int.Int8 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Int.Int16 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Int.Int32 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Int.Int64 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Types.Word GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Word.Word8 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Word.Word16 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Word.Word32 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Word.Word64 GHC.Types.Int instance NumHask.Data.Integral.ToIntegral GHC.Num.Natural.Natural GHC.Num.Natural.Natural instance NumHask.Data.Integral.ToIntegral GHC.Int.Int8 GHC.Int.Int8 instance NumHask.Data.Integral.ToIntegral GHC.Int.Int16 GHC.Int.Int16 instance NumHask.Data.Integral.ToIntegral GHC.Int.Int32 GHC.Int.Int32 instance NumHask.Data.Integral.ToIntegral GHC.Int.Int64 GHC.Int.Int64 instance NumHask.Data.Integral.ToIntegral GHC.Types.Word GHC.Types.Word instance NumHask.Data.Integral.ToIntegral GHC.Word.Word8 GHC.Word.Word8 instance NumHask.Data.Integral.ToIntegral GHC.Word.Word16 GHC.Word.Word16 instance NumHask.Data.Integral.ToIntegral GHC.Word.Word32 GHC.Word.Word32 instance NumHask.Data.Integral.ToIntegral GHC.Word.Word64 GHC.Word.Word64 instance NumHask.Data.Integral.Integral GHC.Types.Int instance NumHask.Data.Integral.Integral GHC.Num.Integer.Integer instance NumHask.Data.Integral.Integral GHC.Num.Natural.Natural instance NumHask.Data.Integral.Integral GHC.Int.Int8 instance NumHask.Data.Integral.Integral GHC.Int.Int16 instance NumHask.Data.Integral.Integral GHC.Int.Int32 instance NumHask.Data.Integral.Integral GHC.Int.Int64 instance NumHask.Data.Integral.Integral GHC.Types.Word instance NumHask.Data.Integral.Integral GHC.Word.Word8 instance NumHask.Data.Integral.Integral GHC.Word.Word16 instance NumHask.Data.Integral.Integral GHC.Word.Word32 instance NumHask.Data.Integral.Integral GHC.Word.Word64 instance NumHask.Data.Integral.Integral b => NumHask.Data.Integral.Integral (a -> b) -- | Field classes module NumHask.Algebra.Field -- | A Semifield is a field with no substraction. type SemiField a = (Distributive a, Divisive a) -- | A Field is a set on which addition, subtraction, -- multiplication, and division are defined. It is also assumed that -- multiplication is distributive over addition. -- -- A summary of the rules inherited from super-classes of Field: -- --
-- zero + a == a -- a + zero == a -- ((a + b) + c) (a + (b + c)) -- a + b == b + a -- a - a == zero -- negate a == zero - a -- negate a + a == zero -- a + negate a == zero -- one * a == a -- a * one == a -- ((a * b) * c) == (a * (b * c)) -- (a * (b + c)) == (a * b + a * c) -- ((a + b) * c) == (a * c + b * c) -- a * zero == zero -- zero * a == zero -- a / a == one || a == zero -- recip a == one / a || a == zero -- recip a * a == one || a == zero -- a * recip a == one || a == zero --type Field a = (Ring a, Divisive a) -- | A hyperbolic field class -- --
-- \a -> a < zero || (sqrt . (**2)) a == a ---- --
-- \a -> a < zero || (log . exp) a ~= a ---- --
-- \a b -> (b < zero) || a <= zero || a == 1 || abs (a ** logBase a b - b) < 10 * epsilon --class (Field a) => ExpField a exp :: ExpField a => a -> a log :: ExpField a => a -> a (**) :: ExpField a => a -> a -> a -- | log to the base of -- --
-- >>> logBase 2 8 -- 2.9999999999999996 --logBase :: ExpField a => a -> a -> a -- | square root -- --
-- >>> sqrt 4 -- 2.0 --sqrt :: ExpField a => a -> a -- | Quotienting of a Field into a Ring -- -- See Field of fractions -- --
-- \a -> a - one < floor a <= a <= ceiling a < a + one --class (SemiField a) => QuotientField a where { type Whole a :: Type; } properFraction :: QuotientField a => a -> (Whole a, a) -- | round to the nearest Int -- -- Exact ties are managed by rounding down ties if the whole component is -- even. -- --
-- >>> round (1.5 :: Double) -- 2 ---- --
-- >>> round (2.5 :: Double) -- 2 --round :: QuotientField a => a -> Whole a -- | round to the nearest Int -- -- Exact ties are managed by rounding down ties if the whole component is -- even. -- --
-- >>> round (1.5 :: Double) -- 2 ---- --
-- >>> round (2.5 :: Double) -- 2 --round :: (QuotientField a, Subtractive a, Integral (Whole a), Eq (Whole a), Ord a, Subtractive (Whole a)) => a -> Whole a -- | supply the next upper whole component -- --
-- >>> ceiling (1.001 :: Double) -- 2 --ceiling :: QuotientField a => a -> Whole a -- | supply the next upper whole component -- --
-- >>> ceiling (1.001 :: Double) -- 2 --ceiling :: (QuotientField a, Ord a, Distributive (Whole a)) => a -> Whole a -- | supply the previous lower whole component -- --
-- >>> floor (1.001 :: Double) -- 1 --floor :: QuotientField a => a -> Whole a -- | supply the previous lower whole component -- --
-- >>> floor (1.001 :: Double) -- 1 --floor :: (QuotientField a, Ord a, Subtractive (Whole a), Distributive (Whole a)) => a -> Whole a -- | supply the whole component closest to zero -- --
-- >>> floor (-1.001 :: Double) -- -2 ---- --
-- >>> truncate (-1.001 :: Double) -- -1 --truncate :: QuotientField a => a -> Whole a -- | supply the whole component closest to zero -- --
-- >>> floor (-1.001 :: Double) -- -2 ---- --
-- >>> truncate (-1.001 :: Double) -- -1 --truncate :: (QuotientField a, Ord a) => a -> Whole a -- | infinity is defined for any Field. -- --
-- >>> one / zero + infinity -- Infinity ---- --
-- >>> infinity + 1 -- Infinity --infinity :: SemiField a => a -- | negative infinity -- --
-- >>> negInfinity + infinity -- NaN --negInfinity :: Field a => a -- | nan is defined as zero/zero -- -- but note the (social) law: -- --
-- >>> nan == zero / zero -- False --nan :: SemiField a => a -- | Trigonometric Field -- -- The list of laws is quite long: trigonometric identities class (Field a) => TrigField a pi :: TrigField a => a sin :: TrigField a => a -> a cos :: TrigField a => a -> a tan :: TrigField a => a -> a asin :: TrigField a => a -> a acos :: TrigField a => a -> a atan :: TrigField a => a -> a atan2 :: TrigField a => a -> a -> a sinh :: TrigField a => a -> a cosh :: TrigField a => a -> a tanh :: TrigField a => a -> a asinh :: TrigField a => a -> a acosh :: TrigField a => a -> a atanh :: TrigField a => a -> a -- | A half of one -- --
-- >>> half :: Double -- 0.5 --half :: (Additive a, Divisive a) => a instance NumHask.Algebra.Field.TrigField GHC.Types.Double instance NumHask.Algebra.Field.TrigField GHC.Types.Float instance NumHask.Algebra.Field.TrigField b => NumHask.Algebra.Field.TrigField (a -> b) instance NumHask.Algebra.Field.QuotientField GHC.Types.Float instance NumHask.Algebra.Field.QuotientField GHC.Types.Double instance NumHask.Algebra.Field.ExpField GHC.Types.Double instance NumHask.Algebra.Field.ExpField GHC.Types.Float instance NumHask.Algebra.Field.ExpField b => NumHask.Algebra.Field.ExpField (a -> b) -- | Lattices module NumHask.Algebra.Lattice -- | A algebraic structure with element joins: See Semilattice -- --
-- Associativity: x \/ (y \/ z) == (x \/ y) \/ z -- Commutativity: x \/ y == y \/ x -- Idempotency: x \/ x == x --class (Eq a) => JoinSemiLattice a (\/) :: JoinSemiLattice a => a -> a -> a infixr 5 \/ -- | The partial ordering induced by the join-semilattice structure joinLeq :: JoinSemiLattice a => a -> a -> Bool -- | The partial ordering induced by the join-semilattice structure (<\) :: JoinSemiLattice a => a -> a -> Bool infixr 6 <\ -- | A algebraic structure with element meets: See Semilattice -- --
-- Associativity: x /\ (y /\ z) == (x /\ y) /\ z -- Commutativity: x /\ y == y /\ x -- Idempotency: x /\ x == x --class (Eq a) => MeetSemiLattice a (/\) :: MeetSemiLattice a => a -> a -> a infixr 6 /\ -- | The partial ordering induced by the meet-semilattice structure meetLeq :: MeetSemiLattice a => a -> a -> Bool -- | The partial ordering induced by the meet-semilattice structure () :: MeetSemiLattice a => a -> a -> Bool infixr 6 -- | A join-semilattice with an identity element bottom for -- \/. -- --
-- x \/ bottom == bottom --class (JoinSemiLattice a) => BoundedJoinSemiLattice a bottom :: BoundedJoinSemiLattice a => a -- | A meet-semilattice with an identity element top for /\. -- --
-- x /\ top == top --class (MeetSemiLattice a) => BoundedMeetSemiLattice a top :: BoundedMeetSemiLattice a => a -- | The combination of two semi lattices makes a lattice if the absorption -- law holds: see Absorption Law and Lattice -- --
-- Absorption: a \/ (a /\ b) == a /\ (a \/ b) == a --type Lattice a = (JoinSemiLattice a, MeetSemiLattice a) -- | Lattices with both bounds -- --
-- x /\ bottom == x -- x \/ top = x --type BoundedLattice a = (JoinSemiLattice a, MeetSemiLattice a, BoundedJoinSemiLattice a, BoundedMeetSemiLattice a) instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Types.Float instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Types.Double instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Types.Int instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Types.Bool instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Int.Int8 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Int.Int16 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Int.Int32 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Int.Int64 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Types.Word instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Word.Word8 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Word.Word16 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Word.Word32 instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice GHC.Word.Word64 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Types.Float instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Types.Double instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Types.Int instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Types.Bool instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Num.Natural.Natural instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Int.Int8 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Int.Int16 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Int.Int32 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Int.Int64 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Types.Word instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Word.Word8 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Word.Word16 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Word.Word32 instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice GHC.Word.Word64 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Types.Float instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Types.Double instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Types.Int instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Num.Integer.Integer instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Types.Bool instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Num.Natural.Natural instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Int.Int8 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Int.Int16 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Int.Int32 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Int.Int64 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Types.Word instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Word.Word8 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Word.Word16 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Word.Word32 instance NumHask.Algebra.Lattice.MeetSemiLattice GHC.Word.Word64 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Types.Float instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Types.Double instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Types.Int instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Num.Integer.Integer instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Types.Bool instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Num.Natural.Natural instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Int.Int8 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Int.Int16 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Int.Int32 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Int.Int64 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Types.Word instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Word.Word8 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Word.Word16 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Word.Word32 instance NumHask.Algebra.Lattice.JoinSemiLattice GHC.Word.Word64 -- | Metric classes module NumHask.Algebra.Metric -- | Basis encapsulates the notion of magnitude (intuitively the -- quotienting of a higher-kinded number to a scalar one) and the basis -- on which the magnitude quotienting was performed. An instance needs to -- satisfy these laws: -- --
-- \a -> magnitude a >= zero -- \a -> magnitude zero == zero -- \a -> a == magnitude a *| basis a -- \a -> magnitude (basis a) == one ---- -- The names chosen are meant to represent the spiritual idea of a basis -- rather than a specific mathematics. See -- https://en.wikipedia.org/wiki/Basis_(linear_algebra) & -- https://en.wikipedia.org/wiki/Norm_(mathematics) for some -- mathematical motivations. -- --
-- >>> magnitude (-0.5 :: Double) -- 0.5 ---- --
-- >>> basis (-0.5 :: Double) -- -1.0 --class (Distributive (Mag a)) => Basis a where { type Mag a :: Type; type Base a :: Type; } -- | or length, or ||v|| magnitude :: Basis a => a -> Mag a -- | or direction, or v-hat basis :: Basis a => a -> Base a -- | Basis where the domain and magnitude codomain are the same. type Absolute a = (Basis a, Mag a ~ a) -- | Basis where the domain and basis codomain are the same. type Sign a = (Basis a, Base a ~ a) -- | Basis where the domain, magnitude codomain and basis codomain are the -- same. type EndoBased a = (Basis a, Mag a ~ a, Base a ~ a) -- | The absolute value of a number. -- --
-- \a -> abs a * signum a ~= a ---- --
-- >>> abs (-1) -- 1 --abs :: Absolute a => a -> a -- | The sign of a number. -- --
-- >>> signum (-1) -- -1 ---- -- abs zero == zero, so any value for signum zero is -- ok. We choose lawful neutral: -- --
-- >>> signum zero == zero -- True --signum :: Sign a => a -> a -- | Distance, which combines the Subtractive notion of difference, with -- Basis. -- --
-- distance a b >= zero -- distance a a == zero -- distance a b *| basis (a - b) == a - b --distance :: (Basis a, Subtractive a) => a -> a -> Mag a -- | Convert between a "co-ordinated" or "higher-kinded" number and a -- direction. -- --
-- ray . angle == basis -- magnitude (ray x) == one --class (Distributive coord, Distributive (Dir coord)) => Direction coord where { type Dir coord :: Type; } angle :: Direction coord => coord -> Dir coord ray :: Direction coord => Dir coord -> coord -- | Something that has a magnitude and a direction, with both expressed as -- the same type. -- -- See Polar coordinate system data Polar a Polar :: a -> a -> Polar a [radial] :: Polar a -> a [azimuth] :: Polar a -> a -- | Convert a higher-kinded number that has direction, to a Polar polar :: (Dir (Base a) ~ Mag a, Basis a, Direction (Base a)) => a -> Polar (Mag a) -- | Convert a Polar to a (higher-kinded) number that has a direction. coord :: (Scalar m ~ Dir m, MultiplicativeAction m, Direction m) => Polar (Scalar m) -> m -- | A small number, especially useful for approximate equality. class (Eq a, Additive a) => Epsilon a epsilon :: Epsilon a => a -- | Note that the constraint is Lattice rather than Ord allowing broader -- usage. -- --
-- >>> nearZero (epsilon :: Double) -- True ---- --
-- >>> nearZero (epsilon :: EuclideanPair Double) -- True --nearZero :: (Epsilon a, Lattice a, Subtractive a) => a -> Bool -- | Approximate equality -- --
-- >>> aboutEqual zero (epsilon :: Double) -- True --aboutEqual :: (Epsilon a, Lattice a, Subtractive a) => a -> a -> Bool -- | About equal operator. -- --
-- >>> (1.0 + epsilon) ~= (1.0 :: Double) -- True --(~=) :: Epsilon a => (Lattice a, Subtractive a) => a -> a -> Bool infixl 4 ~= -- | Two dimensional cartesian coordinates. newtype EuclideanPair a EuclideanPair :: (a, a) -> EuclideanPair a [euclidPair] :: EuclideanPair a -> (a, a) instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Algebra.Metric.Polar a) instance GHC.Show.Show a => GHC.Show.Show (NumHask.Algebra.Metric.Polar a) instance GHC.Generics.Generic (NumHask.Algebra.Metric.Polar a) instance GHC.Show.Show a => GHC.Show.Show (NumHask.Algebra.Metric.EuclideanPair a) instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Algebra.Metric.EuclideanPair a) instance GHC.Generics.Generic (NumHask.Algebra.Metric.EuclideanPair a) instance GHC.Base.Functor NumHask.Algebra.Metric.EuclideanPair instance GHC.Base.Applicative NumHask.Algebra.Metric.EuclideanPair instance NumHask.Algebra.Additive.Additive a => NumHask.Algebra.Additive.Additive (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Additive.Subtractive a => NumHask.Algebra.Additive.Subtractive (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Multiplicative.Multiplicative a => NumHask.Algebra.Multiplicative.Multiplicative (NumHask.Algebra.Metric.EuclideanPair a) instance (NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Multiplicative.Divisive a) => NumHask.Algebra.Multiplicative.Divisive (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Field.TrigField a => NumHask.Algebra.Metric.Direction (NumHask.Algebra.Metric.EuclideanPair a) instance (NumHask.Algebra.Field.ExpField a, GHC.Classes.Eq a) => NumHask.Algebra.Metric.Basis (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Metric.Epsilon a => NumHask.Algebra.Metric.Epsilon (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Lattice.JoinSemiLattice a => NumHask.Algebra.Lattice.JoinSemiLattice (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Lattice.MeetSemiLattice a => NumHask.Algebra.Lattice.MeetSemiLattice (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice a => NumHask.Algebra.Lattice.BoundedJoinSemiLattice (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice a => NumHask.Algebra.Lattice.BoundedMeetSemiLattice (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Multiplicative.Multiplicative a => NumHask.Algebra.Action.MultiplicativeAction (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Multiplicative.Divisive a => NumHask.Algebra.Action.DivisiveAction (NumHask.Algebra.Metric.EuclideanPair a) instance (GHC.Classes.Ord a, NumHask.Algebra.Field.TrigField a, NumHask.Algebra.Field.ExpField a) => NumHask.Algebra.Field.ExpField (NumHask.Algebra.Metric.EuclideanPair a) instance (NumHask.Algebra.Field.QuotientField a, NumHask.Algebra.Additive.Subtractive a) => NumHask.Algebra.Field.QuotientField (NumHask.Algebra.Metric.EuclideanPair a) instance NumHask.Algebra.Metric.Epsilon GHC.Types.Double instance NumHask.Algebra.Metric.Epsilon GHC.Types.Float instance NumHask.Algebra.Metric.Epsilon GHC.Types.Int instance NumHask.Algebra.Metric.Epsilon GHC.Num.Integer.Integer instance NumHask.Algebra.Metric.Epsilon GHC.Int.Int8 instance NumHask.Algebra.Metric.Epsilon GHC.Int.Int16 instance NumHask.Algebra.Metric.Epsilon GHC.Int.Int32 instance NumHask.Algebra.Metric.Epsilon GHC.Int.Int64 instance NumHask.Algebra.Metric.Epsilon GHC.Types.Word instance NumHask.Algebra.Metric.Epsilon GHC.Word.Word8 instance NumHask.Algebra.Metric.Epsilon GHC.Word.Word16 instance NumHask.Algebra.Metric.Epsilon GHC.Word.Word32 instance NumHask.Algebra.Metric.Epsilon GHC.Word.Word64 instance (NumHask.Algebra.Additive.Additive a, NumHask.Algebra.Multiplicative.Multiplicative a) => NumHask.Algebra.Metric.Basis (NumHask.Algebra.Metric.Polar a) instance NumHask.Algebra.Metric.Basis GHC.Types.Double instance NumHask.Algebra.Metric.Basis GHC.Types.Float instance NumHask.Algebra.Metric.Basis GHC.Types.Int instance NumHask.Algebra.Metric.Basis GHC.Num.Integer.Integer instance NumHask.Algebra.Metric.Basis GHC.Num.Natural.Natural instance NumHask.Algebra.Metric.Basis GHC.Int.Int8 instance NumHask.Algebra.Metric.Basis GHC.Int.Int16 instance NumHask.Algebra.Metric.Basis GHC.Int.Int32 instance NumHask.Algebra.Metric.Basis GHC.Int.Int64 instance NumHask.Algebra.Metric.Basis GHC.Types.Word instance NumHask.Algebra.Metric.Basis GHC.Word.Word8 instance NumHask.Algebra.Metric.Basis GHC.Word.Word16 instance NumHask.Algebra.Metric.Basis GHC.Word.Word32 instance NumHask.Algebra.Metric.Basis GHC.Word.Word64 -- | Complex numbers. module NumHask.Data.Complex -- | The underlying representation is a newtype-wrapped tuple, compared -- with the base datatype. This was chosen to facilitate the use of -- DerivingVia. newtype Complex a Complex :: (a, a) -> Complex a [complexPair] :: Complex a -> (a, a) -- | Complex number constructor. (+:) :: a -> a -> Complex a infixl 6 +: -- | Extracts the real part of a complex number. realPart :: Complex a -> a -- | Extracts the imaginary part of a complex number. imagPart :: Complex a -> a instance (GHC.Classes.Ord a, NumHask.Algebra.Field.TrigField a, NumHask.Algebra.Field.ExpField a) => NumHask.Algebra.Field.ExpField (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice a => NumHask.Algebra.Lattice.BoundedMeetSemiLattice (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice a => NumHask.Algebra.Lattice.BoundedJoinSemiLattice (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Lattice.MeetSemiLattice a => NumHask.Algebra.Lattice.MeetSemiLattice (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Lattice.JoinSemiLattice a => NumHask.Algebra.Lattice.JoinSemiLattice (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Metric.Epsilon a => NumHask.Algebra.Metric.Epsilon (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Field.TrigField a => NumHask.Algebra.Metric.Direction (NumHask.Data.Complex.Complex a) instance (NumHask.Algebra.Field.ExpField a, GHC.Classes.Eq a) => NumHask.Algebra.Metric.Basis (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Additive.Subtractive a => NumHask.Algebra.Additive.Subtractive (NumHask.Data.Complex.Complex a) instance NumHask.Algebra.Additive.Additive a => NumHask.Algebra.Additive.Additive (NumHask.Data.Complex.Complex a) instance GHC.Base.Functor NumHask.Data.Complex.Complex instance GHC.Generics.Generic (NumHask.Data.Complex.Complex a) instance Data.Data.Data a => Data.Data.Data (NumHask.Data.Complex.Complex a) instance GHC.Read.Read a => GHC.Read.Read (NumHask.Data.Complex.Complex a) instance GHC.Show.Show a => GHC.Show.Show (NumHask.Data.Complex.Complex a) instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Data.Complex.Complex a) instance (NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Multiplicative.Multiplicative a) => NumHask.Algebra.Multiplicative.Multiplicative (NumHask.Data.Complex.Complex a) instance (NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Multiplicative.Divisive a) => NumHask.Algebra.Multiplicative.Divisive (NumHask.Data.Complex.Complex a) instance (NumHask.Algebra.Additive.Additive a, NumHask.Data.Integral.FromIntegral a b) => NumHask.Data.Integral.FromIntegral (NumHask.Data.Complex.Complex a) b instance (NumHask.Algebra.Ring.Distributive a, NumHask.Algebra.Additive.Subtractive a) => NumHask.Algebra.Ring.InvolutiveRing (NumHask.Data.Complex.Complex a) instance (NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Field.QuotientField a) => NumHask.Algebra.Field.QuotientField (NumHask.Data.Complex.Complex a) -- | Rational classes module NumHask.Data.Rational -- | A rational number, represented as the ratio of two Integral -- numbers. data Ratio a (:%) :: !a -> !a -> Ratio a -- | Ratio of two integers type Rational = Ratio Integer -- | toRatio is equivalent to Real in base, but is polymorphic in -- the Integral type. -- --
-- >>> toRatio (3.1415927 :: Float) :: Ratio Integer -- 13176795 :% 4194304 --class ToRatio a b toRatio :: ToRatio a b => a -> Ratio b -- | Fractional in base splits into fromRatio and Field -- --
-- >>> fromRatio (5 :% 2 :: Ratio Integer) :: Double -- 2.5 --class FromRatio a b fromRatio :: FromRatio a b => Ratio b -> a -- | fromRational is special in two ways: -- --
-- >>> reduce 72 60 -- 6 :% 5 ---- --
-- \a b -> reduce a b == a :% b || b == zero --reduce :: (Eq a, Subtractive a, EndoBased a, Integral a) => a -> a -> Ratio a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. -- --
-- >>> gcd 72 60 -- 12 --gcd :: (Eq a, EndoBased a, Integral a) => a -> a -> a instance GHC.Show.Show a => GHC.Show.Show (NumHask.Data.Rational.Ratio a) instance NumHask.Data.Rational.FromRational GHC.Types.Double instance NumHask.Data.Rational.FromRational GHC.Types.Float instance NumHask.Data.Rational.FromRational (NumHask.Data.Rational.Ratio GHC.Num.Integer.Integer) instance NumHask.Data.Rational.FromRatio GHC.Types.Double GHC.Num.Integer.Integer instance NumHask.Data.Rational.FromRatio GHC.Types.Float GHC.Num.Integer.Integer instance NumHask.Data.Rational.FromRatio NumHask.Data.Rational.Rational GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Types.Double GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Types.Float GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio (NumHask.Data.Rational.Ratio GHC.Num.Integer.Integer) GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Types.Int GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Num.Integer.Integer GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Num.Natural.Natural GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Int.Int8 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Int.Int16 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Int.Int32 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Int.Int64 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Types.Word GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Word.Word8 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Word.Word16 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Word.Word32 GHC.Num.Integer.Integer instance NumHask.Data.Rational.ToRatio GHC.Word.Word64 GHC.Num.Integer.Integer instance (GHC.Classes.Eq a, NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Metric.EndoBased a, NumHask.Algebra.Metric.Absolute a, NumHask.Data.Integral.Integral a) => GHC.Classes.Eq (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Metric.EndoBased a, NumHask.Algebra.Additive.Subtractive a) => GHC.Classes.Ord (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a) => NumHask.Algebra.Additive.Additive (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a) => NumHask.Algebra.Additive.Subtractive (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a) => NumHask.Algebra.Multiplicative.Multiplicative (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a) => NumHask.Algebra.Multiplicative.Divisive (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Algebra.Metric.Absolute a, NumHask.Data.Integral.ToInt a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a) => NumHask.Algebra.Field.QuotientField (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a) => NumHask.Algebra.Metric.Basis (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Metric.EndoBased a, NumHask.Algebra.Additive.Subtractive a) => NumHask.Algebra.Lattice.JoinSemiLattice (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Metric.EndoBased a, NumHask.Algebra.Additive.Subtractive a) => NumHask.Algebra.Lattice.MeetSemiLattice (NumHask.Data.Rational.Ratio a) instance (GHC.Classes.Ord a, NumHask.Algebra.Metric.EndoBased a, NumHask.Data.Integral.Integral a, NumHask.Algebra.Ring.Ring a, NumHask.Algebra.Lattice.MeetSemiLattice a) => NumHask.Algebra.Metric.Epsilon (NumHask.Data.Rational.Ratio a) instance (NumHask.Data.Integral.FromIntegral a b, NumHask.Algebra.Multiplicative.Multiplicative a) => NumHask.Data.Integral.FromIntegral (NumHask.Data.Rational.Ratio a) b -- | Wrapped numhask instances, useful for derivingvia situations to -- quickly specifiy a numhask friendly numerical type. module NumHask.Data.Wrapped -- | Wrapped numhask instances newtype Wrapped a Wrapped :: a -> Wrapped a [unWrapped] :: Wrapped a -> a instance NumHask.Algebra.Action.DivisiveAction a => NumHask.Algebra.Action.DivisiveAction (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Action.MultiplicativeAction a => NumHask.Algebra.Action.MultiplicativeAction (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Action.SubtractiveAction a => NumHask.Algebra.Action.SubtractiveAction (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Action.AdditiveAction a => NumHask.Algebra.Action.AdditiveAction (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Metric.Epsilon a => NumHask.Algebra.Metric.Epsilon (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Metric.Direction a => NumHask.Algebra.Metric.Direction (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Metric.Basis a => NumHask.Algebra.Metric.Basis (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice a => NumHask.Algebra.Lattice.BoundedMeetSemiLattice (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Lattice.BoundedJoinSemiLattice a => NumHask.Algebra.Lattice.BoundedJoinSemiLattice (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Lattice.JoinSemiLattice a => NumHask.Algebra.Lattice.JoinSemiLattice (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Lattice.MeetSemiLattice a => NumHask.Algebra.Lattice.MeetSemiLattice (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Data.Rational.FromRational a => NumHask.Data.Rational.FromRational (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Data.Integral.FromInteger a => NumHask.Data.Integral.FromInteger (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Data.Integral.Integral a => NumHask.Data.Integral.Integral (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Ring.InvolutiveRing a => NumHask.Algebra.Ring.InvolutiveRing (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Ring.StarSemiring a => NumHask.Algebra.Ring.StarSemiring (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Field.TrigField a => NumHask.Algebra.Field.TrigField (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Field.ExpField a => NumHask.Algebra.Field.ExpField (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Multiplicative.Divisive a => NumHask.Algebra.Multiplicative.Divisive (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Multiplicative.Multiplicative a => NumHask.Algebra.Multiplicative.Multiplicative (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Additive.Subtractive a => NumHask.Algebra.Additive.Subtractive (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Algebra.Additive.Additive a => NumHask.Algebra.Additive.Additive (NumHask.Data.Wrapped.Wrapped a) instance GHC.Classes.Ord a => GHC.Classes.Ord (NumHask.Data.Wrapped.Wrapped a) instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Data.Wrapped.Wrapped a) instance GHC.Show.Show a => GHC.Show.Show (NumHask.Data.Wrapped.Wrapped a) instance (GHC.Classes.Ord a, GHC.Classes.Eq (NumHask.Algebra.Field.Whole a), NumHask.Data.Integral.Integral (NumHask.Algebra.Field.Whole a), NumHask.Algebra.Additive.Subtractive (NumHask.Algebra.Field.Whole a), NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Field.QuotientField a) => NumHask.Algebra.Field.QuotientField (NumHask.Data.Wrapped.Wrapped a) instance NumHask.Data.Integral.FromIntegral a b => NumHask.Data.Integral.FromIntegral (NumHask.Data.Wrapped.Wrapped a) b instance NumHask.Data.Integral.ToIntegral a b => NumHask.Data.Integral.ToIntegral (NumHask.Data.Wrapped.Wrapped a) b instance NumHask.Data.Rational.FromRatio a b => NumHask.Data.Rational.FromRatio (NumHask.Data.Wrapped.Wrapped a) b instance NumHask.Data.Rational.ToRatio a b => NumHask.Data.Rational.ToRatio (NumHask.Data.Wrapped.Wrapped a) b -- | A positive number type, defined as existing on [zero, +infinity) module NumHask.Data.Positive -- | A positive number is a number that is contained in [zero,+infinity). -- --
-- >>> 1 :: Positive Int
-- UnsafePositive {unPositive = 1}
--
--
-- -- >>> -1 :: Positive Int -- ... -- • No instance for ‘Subtractive (Positive Int)’ -- arising from a use of syntactic negation -- ... ---- -- zero is positive -- --
-- >>> positive 0 == zero -- True ---- -- The main constructors: -- --
-- >>> positive (-1)
-- UnsafePositive {unPositive = 0}
--
--
-- -- >>> maybePositive (-1) -- Nothing ---- --
-- >>> UnsafePositive (-1)
-- UnsafePositive {unPositive = -1}
--
newtype Positive a
UnsafePositive :: a -> Positive a
[unPositive] :: Positive a -> a
-- | Constructor which returns zero for a negative number.
--
--
-- >>> positive (-1)
-- UnsafePositive {unPositive = 0}
--
positive :: (Additive a, MeetSemiLattice a) => a -> Positive a
-- | Constructor which returns Nothing if a negative number is supplied.
--
-- -- >>> maybePositive (-one) -- Nothing --maybePositive :: (Additive a, MeetSemiLattice a) => a -> Maybe (Positive a) -- | Unsafe constructor. -- --
-- >>> positive_ (-one)
-- UnsafePositive {unPositive = -1}
--
positive_ :: a -> Positive a
-- | Monus or truncated subtraction.
--
--
-- >>> positive 4 ∸ positive 7
-- UnsafePositive {unPositive = 0}
--
--
--
-- >>> 4 ∸ 7 :: Positive Int
-- UnsafePositive {unPositive = 0}
--
class Monus a
(∸) :: Monus a => a -> a -> a
(∸) :: (Monus a, BoundedJoinSemiLattice a, MeetSemiLattice a, Subtractive a) => a -> a -> a
infixl 6 ∸
-- | Truncated addition
class Addus a
(∔) :: Addus a => a -> a -> a
(∔) :: (Addus a, BoundedMeetSemiLattice a, JoinSemiLattice a, Additive a) => a -> a -> a
infixl 6 ∔
-- | A field but with truncated subtraction.
type MonusSemiField a = (Monus a, Distributive a, Divisive a)
instance NumHask.Algebra.Lattice.BoundedMeetSemiLattice a => NumHask.Algebra.Lattice.BoundedMeetSemiLattice (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Lattice.MeetSemiLattice a => NumHask.Algebra.Lattice.MeetSemiLattice (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Lattice.JoinSemiLattice a => NumHask.Algebra.Lattice.JoinSemiLattice (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Action.DivisiveAction a => NumHask.Algebra.Action.DivisiveAction (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Action.MultiplicativeAction a => NumHask.Algebra.Action.MultiplicativeAction (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Action.SubtractiveAction a => NumHask.Algebra.Action.SubtractiveAction (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Action.AdditiveAction a => NumHask.Algebra.Action.AdditiveAction (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Metric.Epsilon a => NumHask.Algebra.Metric.Epsilon (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Metric.Direction a => NumHask.Algebra.Metric.Direction (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Metric.Basis a => NumHask.Algebra.Metric.Basis (NumHask.Data.Positive.Positive a)
instance NumHask.Data.Rational.FromRational a => NumHask.Data.Rational.FromRational (NumHask.Data.Positive.Positive a)
instance NumHask.Data.Integral.FromInteger a => NumHask.Data.Integral.FromInteger (NumHask.Data.Positive.Positive a)
instance NumHask.Data.Integral.Integral a => NumHask.Data.Integral.Integral (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Multiplicative.Divisive a => NumHask.Algebra.Multiplicative.Divisive (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Multiplicative.Multiplicative a => NumHask.Algebra.Multiplicative.Multiplicative (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Additive.Additive a => NumHask.Algebra.Additive.Additive (NumHask.Data.Positive.Positive a)
instance GHC.Show.Show a => GHC.Show.Show (NumHask.Data.Positive.Positive a)
instance GHC.Classes.Ord a => GHC.Classes.Ord (NumHask.Data.Positive.Positive a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (NumHask.Data.Positive.Positive a)
instance (NumHask.Algebra.Additive.Subtractive a, NumHask.Algebra.Lattice.MeetSemiLattice a) => NumHask.Data.Positive.Monus (NumHask.Data.Positive.Positive a)
instance (NumHask.Algebra.Lattice.MeetSemiLattice a, NumHask.Data.Integral.Integral a) => NumHask.Data.Integral.FromIntegral (NumHask.Data.Positive.Positive a) a
instance NumHask.Data.Integral.FromIntegral a b => NumHask.Data.Integral.FromIntegral (NumHask.Data.Positive.Positive a) b
instance NumHask.Data.Integral.ToIntegral a b => NumHask.Data.Integral.ToIntegral (NumHask.Data.Positive.Positive a) b
instance NumHask.Data.Rational.FromRatio a b => NumHask.Data.Rational.FromRatio (NumHask.Data.Positive.Positive a) b
instance NumHask.Data.Rational.ToRatio a b => NumHask.Data.Rational.ToRatio (NumHask.Data.Positive.Positive a) b
instance (NumHask.Algebra.Additive.Additive a, NumHask.Algebra.Lattice.JoinSemiLattice a) => NumHask.Algebra.Lattice.BoundedJoinSemiLattice (NumHask.Data.Positive.Positive a)
instance NumHask.Algebra.Field.QuotientField (NumHask.Data.Positive.Positive GHC.Types.Double)
-- | Exceptions arising within numhask.
module NumHask.Exception
-- | A numhask exception.
newtype NumHaskException
NumHaskException :: String -> NumHaskException
[errorMessage] :: NumHaskException -> String
-- | Throw an exception. Exceptions may be thrown from purely functional
-- code, but may only be caught within the IO monad.
--
-- WARNING: You may want to use throwIO instead so that your
-- pure code stays exception-free.
throw :: forall (r :: RuntimeRep) (a :: TYPE r) e. Exception e => e -> a
instance GHC.Show.Show NumHask.Exception.NumHaskException
instance GHC.Exception.Type.Exception NumHask.Exception.NumHaskException
-- | Numeric classes.
module NumHask
-- | or Addition
--
-- For practical reasons, we begin the class tree with Additive.
-- Starting with Associative and Unital, or using
-- Semigroup and Monoid from base tends to confuse the
-- interface once you start having to disinguish between (say) monoidal
-- addition and monoidal multiplication.
--
-- -- \a -> zero + a == a ---- --
-- \a -> a + zero == a ---- --
-- \a b c -> (a + b) + c == a + (b + c) ---- --
-- \a b -> a + b == b + a ---- -- By convention, (+) is regarded as commutative, but this is not -- universal, and the introduction of another symbol which means -- non-commutative addition seems a bit dogmatic. -- --
-- >>> zero + 1 -- 1 ---- --
-- >>> 1 + 1 -- 2 --class Additive a (+) :: Additive a => a -> a -> a zero :: Additive a => a infixl 6 + -- | Compute the sum of a Foldable. -- --
-- >>> sum [0..10] -- 55 --sum :: (Additive a, Foldable f) => f a -> a -- | Compute the accumulating sum of a Traversable. -- --
-- >>> accsum [0..10] -- [0,1,3,6,10,15,21,28,36,45,55] --accsum :: (Additive a, Traversable f) => f a -> f a -- | or Subtraction -- --
-- \a -> a - a == zero ---- --
-- \a -> negate a == zero - a ---- --
-- \a -> negate a + a == zero ---- --
-- \a -> a + negate a == zero ---- --
-- >>> negate 1 -- -1 ---- --
-- >>> 1 - 2 -- -1 --class (Additive a) => Subtractive a negate :: Subtractive a => a -> a (-) :: Subtractive a => a -> a -> a infixl 6 - -- | or Multiplication -- -- For practical reasons, we begin the class tree with Additive -- and Multiplicative. Starting with Associative and -- Unital, or using Semigroup and Monoid from base -- tends to confuse the interface once you start having to disinguish -- between (say) monoidal addition and monoidal multiplication. -- --
-- \a -> one * a == a ---- --
-- \a -> a * one == a ---- --
-- \a b c -> (a * b) * c == a * (b * c) ---- -- By convention, (*) is regarded as not necessarily commutative, but -- this is not universal, and the introduction of another symbol which -- means commutative multiplication seems a bit dogmatic. -- --
-- >>> one * 2 -- 2 ---- --
-- >>> 2 * 3 -- 6 --class Multiplicative a (*) :: Multiplicative a => a -> a -> a one :: Multiplicative a => a infixl 7 * -- | Compute the product of a Foldable. -- --
-- >>> product [1..5] -- 120 --product :: (Multiplicative a, Foldable f) => f a -> a -- | Compute the accumulating product of a Traversable. -- --
-- >>> accproduct [1..5] -- [1,2,6,24,120] --accproduct :: (Multiplicative a, Traversable f) => f a -> f a -- | or Division -- -- Though unusual, the term Divisive usefully fits in with the grammer of -- other classes and avoids name clashes that occur with some popular -- libraries. -- --
-- \(a :: Double) -> a / a ~= one || a == zero ---- --
-- \(a :: Double) -> recip a ~= one / a || a == zero ---- --
-- \(a :: Double) -> recip a * a ~= one || a == zero ---- --
-- \(a :: Double) -> a * recip a ~= one || a == zero ---- --
-- >>> recip 2.0 -- 0.5 ---- --
-- >>> 1 / 2 -- 0.5 --class (Multiplicative a) => Divisive a recip :: Divisive a => a -> a (/) :: Divisive a => a -> a -> a infixl 7 / -- | Distributive -- --
-- \a b c -> a * (b + c) == a * b + a * c ---- --
-- \a b c -> (a + b) * c == a * c + b * c ---- --
-- \a -> zero * a == zero ---- --
-- \a -> a * zero == zero ---- -- The sneaking in of the Absorption laws here glosses over the -- possibility that the multiplicative zero element does not have to -- correspond with the additive unital zero. type Distributive a = (Additive a, Multiplicative a) -- | A Ring is an abelian group under addition (Unital, -- Associative, Commutative, Invertible) and -- monoidal under multiplication (Unital, Associative), and -- where multiplication distributes over addition. -- --
-- \a -> zero + a == a -- \a -> a + zero == a -- \a b c -> (a + b) + c == a + (b + c) -- \a b -> a + b == b + a -- \a -> a - a == zero -- \a -> negate a == zero - a -- \a -> negate a + a == zero -- \a -> a + negate a == zero -- \a -> one * a == a -- \a -> a * one == a -- \a b c -> (a * b) * c == a * (b * c) -- \a b c -> a * (b + c) == a * b + a * c -- \a b c -> (a + b) * c == a * c + b * c -- \a -> zero * a == zero -- \a -> a * zero == zero --type Ring a = (Distributive a, Subtractive a) -- | A StarSemiring is a semiring with an additional unary operator -- (star) satisfying: -- --
-- \a -> star a == one + a * star a --class (Distributive a) => StarSemiring a star :: StarSemiring a => a -> a plus :: StarSemiring a => a -> a -- | A Kleene Algebra is a Star Semiring with idempotent addition. -- --
-- a * x + x = a ==> star a * x + x = x -- x * a + x = a ==> x * star a + x = x --class (StarSemiring a, Idempotent a) => KleeneAlgebra a -- | Involutive Ring -- --
-- adj (a + b) ==> adj a + adj b -- adj (a * b) ==> adj a * adj b -- adj one ==> one -- adj (adj a) ==> a ---- -- Note: elements for which adj a == a are called -- "self-adjoint". class (Distributive a) => InvolutiveRing a adj :: InvolutiveRing a => a -> a -- | Defining two requires adding the multiplicative unital to -- itself. In other words, the concept of two is a Ring one. -- --
-- >>> two -- 2 --two :: (Multiplicative a, Additive a) => a -- | A Field is a set on which addition, subtraction, -- multiplication, and division are defined. It is also assumed that -- multiplication is distributive over addition. -- -- A summary of the rules inherited from super-classes of Field: -- --
-- zero + a == a -- a + zero == a -- ((a + b) + c) (a + (b + c)) -- a + b == b + a -- a - a == zero -- negate a == zero - a -- negate a + a == zero -- a + negate a == zero -- one * a == a -- a * one == a -- ((a * b) * c) == (a * (b * c)) -- (a * (b + c)) == (a * b + a * c) -- ((a + b) * c) == (a * c + b * c) -- a * zero == zero -- zero * a == zero -- a / a == one || a == zero -- recip a == one / a || a == zero -- recip a * a == one || a == zero -- a * recip a == one || a == zero --type Field a = (Ring a, Divisive a) -- | A hyperbolic field class -- --
-- \a -> a < zero || (sqrt . (**2)) a == a ---- --
-- \a -> a < zero || (log . exp) a ~= a ---- --
-- \a b -> (b < zero) || a <= zero || a == 1 || abs (a ** logBase a b - b) < 10 * epsilon --class (Field a) => ExpField a exp :: ExpField a => a -> a log :: ExpField a => a -> a (**) :: ExpField a => a -> a -> a -- | log to the base of -- --
-- >>> logBase 2 8 -- 2.9999999999999996 --logBase :: ExpField a => a -> a -> a -- | square root -- --
-- >>> sqrt 4 -- 2.0 --sqrt :: ExpField a => a -> a -- | Quotienting of a Field into a Ring -- -- See Field of fractions -- --
-- \a -> a - one < floor a <= a <= ceiling a < a + one --class (SemiField a) => QuotientField a where { type Whole a :: Type; } properFraction :: QuotientField a => a -> (Whole a, a) -- | round to the nearest Int -- -- Exact ties are managed by rounding down ties if the whole component is -- even. -- --
-- >>> round (1.5 :: Double) -- 2 ---- --
-- >>> round (2.5 :: Double) -- 2 --round :: QuotientField a => a -> Whole a -- | round to the nearest Int -- -- Exact ties are managed by rounding down ties if the whole component is -- even. -- --
-- >>> round (1.5 :: Double) -- 2 ---- --
-- >>> round (2.5 :: Double) -- 2 --round :: (QuotientField a, Subtractive a, Integral (Whole a), Eq (Whole a), Ord a, Subtractive (Whole a)) => a -> Whole a -- | supply the next upper whole component -- --
-- >>> ceiling (1.001 :: Double) -- 2 --ceiling :: QuotientField a => a -> Whole a -- | supply the next upper whole component -- --
-- >>> ceiling (1.001 :: Double) -- 2 --ceiling :: (QuotientField a, Ord a, Distributive (Whole a)) => a -> Whole a -- | supply the previous lower whole component -- --
-- >>> floor (1.001 :: Double) -- 1 --floor :: QuotientField a => a -> Whole a -- | supply the previous lower whole component -- --
-- >>> floor (1.001 :: Double) -- 1 --floor :: (QuotientField a, Ord a, Subtractive (Whole a), Distributive (Whole a)) => a -> Whole a -- | supply the whole component closest to zero -- --
-- >>> floor (-1.001 :: Double) -- -2 ---- --
-- >>> truncate (-1.001 :: Double) -- -1 --truncate :: QuotientField a => a -> Whole a -- | supply the whole component closest to zero -- --
-- >>> floor (-1.001 :: Double) -- -2 ---- --
-- >>> truncate (-1.001 :: Double) -- -1 --truncate :: (QuotientField a, Ord a) => a -> Whole a -- | Trigonometric Field -- -- The list of laws is quite long: trigonometric identities class (Field a) => TrigField a pi :: TrigField a => a sin :: TrigField a => a -> a cos :: TrigField a => a -> a tan :: TrigField a => a -> a asin :: TrigField a => a -> a acos :: TrigField a => a -> a atan :: TrigField a => a -> a atan2 :: TrigField a => a -> a -> a sinh :: TrigField a => a -> a cosh :: TrigField a => a -> a tanh :: TrigField a => a -> a asinh :: TrigField a => a -> a acosh :: TrigField a => a -> a atanh :: TrigField a => a -> a -- | infinity is defined for any Field. -- --
-- >>> one / zero + infinity -- Infinity ---- --
-- >>> infinity + 1 -- Infinity --infinity :: SemiField a => a -- | negative infinity -- --
-- >>> negInfinity + infinity -- NaN --negInfinity :: Field a => a -- | nan is defined as zero/zero -- -- but note the (social) law: -- --
-- >>> nan == zero / zero -- False --nan :: SemiField a => a -- | A half of one -- --
-- >>> half :: Double -- 0.5 --half :: (Additive a, Divisive a) => a -- | A algebraic structure with element joins: See Semilattice -- --
-- Associativity: x \/ (y \/ z) == (x \/ y) \/ z -- Commutativity: x \/ y == y \/ x -- Idempotency: x \/ x == x --class (Eq a) => JoinSemiLattice a (\/) :: JoinSemiLattice a => a -> a -> a infixr 5 \/ -- | The partial ordering induced by the join-semilattice structure joinLeq :: JoinSemiLattice a => a -> a -> Bool -- | The partial ordering induced by the join-semilattice structure (<\) :: JoinSemiLattice a => a -> a -> Bool infixr 6 <\ -- | A algebraic structure with element meets: See Semilattice -- --
-- Associativity: x /\ (y /\ z) == (x /\ y) /\ z -- Commutativity: x /\ y == y /\ x -- Idempotency: x /\ x == x --class (Eq a) => MeetSemiLattice a (/\) :: MeetSemiLattice a => a -> a -> a infixr 6 /\ -- | The partial ordering induced by the meet-semilattice structure meetLeq :: MeetSemiLattice a => a -> a -> Bool -- | The partial ordering induced by the meet-semilattice structure () :: MeetSemiLattice a => a -> a -> Bool infixr 6 -- | A join-semilattice with an identity element bottom for -- \/. -- --
-- x \/ bottom == bottom --class (JoinSemiLattice a) => BoundedJoinSemiLattice a bottom :: BoundedJoinSemiLattice a => a -- | A meet-semilattice with an identity element top for /\. -- --
-- x /\ top == top --class (MeetSemiLattice a) => BoundedMeetSemiLattice a top :: BoundedMeetSemiLattice a => a -- | Additive Action -- --
-- m |+ zero == m --class (Additive (AdditiveScalar m)) => AdditiveAction m where { type AdditiveScalar m :: Type; } (|+) :: AdditiveAction m => m -> AdditiveScalar m -> m infixl 6 |+ -- | flipped additive action -- --
-- (+|) == flip (|+) -- zero +| m = m --(+|) :: AdditiveAction m => AdditiveScalar m -> m -> m infixl 6 +| -- | Subtractive Action -- --
-- m |- zero = m --class (AdditiveAction m, Subtractive (AdditiveScalar m)) => SubtractiveAction m (|-) :: SubtractiveAction m => m -> AdditiveScalar m -> m infixl 6 |- -- | Subtraction with the scalar on the left -- --
-- (-|) == (+|) . negate -- zero -| m = negate m --(-|) :: (AdditiveAction m, Subtractive m) => AdditiveScalar m -> m -> m infixl 6 -| -- | Multiplicative Action -- --
-- m |* one = m -- m |* zero = zero --class (Multiplicative (Scalar m)) => MultiplicativeAction m where { type Scalar m :: Type; } (|*) :: MultiplicativeAction m => m -> Scalar m -> m infixl 7 |* -- | flipped multiplicative action -- --
-- (*|) == flip (|*) -- one *| m = one -- zero *| m = zero --(*|) :: MultiplicativeAction m => Scalar m -> m -> m infixl 7 *| -- | Divisive Action -- --
-- m |/ one = m --class (Divisive (Scalar m), MultiplicativeAction m) => DivisiveAction m (|/) :: DivisiveAction m => m -> Scalar m -> m infixl 7 |/ -- | left scalar division -- --
-- (/|) == (*|) . recip -- one |/ m = recip m --(/|) :: (MultiplicativeAction m, Divisive m) => Scalar m -> m -> m -- | A Module -- --
-- a *| one == a -- (a + b) *| c == (a *| c) + (b *| c) -- c |* (a + b) == (c |* a) + (c |* b) -- a *| zero == zero -- a *| b == b |* a --type Module m = (Distributive (Scalar m), MultiplicativeAction m) -- | Basis encapsulates the notion of magnitude (intuitively the -- quotienting of a higher-kinded number to a scalar one) and the basis -- on which the magnitude quotienting was performed. An instance needs to -- satisfy these laws: -- --
-- \a -> magnitude a >= zero -- \a -> magnitude zero == zero -- \a -> a == magnitude a *| basis a -- \a -> magnitude (basis a) == one ---- -- The names chosen are meant to represent the spiritual idea of a basis -- rather than a specific mathematics. See -- https://en.wikipedia.org/wiki/Basis_(linear_algebra) & -- https://en.wikipedia.org/wiki/Norm_(mathematics) for some -- mathematical motivations. -- --
-- >>> magnitude (-0.5 :: Double) -- 0.5 ---- --
-- >>> basis (-0.5 :: Double) -- -1.0 --class (Distributive (Mag a)) => Basis a where { type Mag a :: Type; type Base a :: Type; } -- | or length, or ||v|| magnitude :: Basis a => a -> Mag a -- | or direction, or v-hat basis :: Basis a => a -> Base a -- | Basis where the domain and magnitude codomain are the same. type Absolute a = (Basis a, Mag a ~ a) -- | Basis where the domain and basis codomain are the same. type Sign a = (Basis a, Base a ~ a) -- | Basis where the domain, magnitude codomain and basis codomain are the -- same. type EndoBased a = (Basis a, Mag a ~ a, Base a ~ a) -- | The absolute value of a number. -- --
-- \a -> abs a * signum a ~= a ---- --
-- >>> abs (-1) -- 1 --abs :: Absolute a => a -> a -- | The sign of a number. -- --
-- >>> signum (-1) -- -1 ---- -- abs zero == zero, so any value for signum zero is -- ok. We choose lawful neutral: -- --
-- >>> signum zero == zero -- True --signum :: Sign a => a -> a -- | Distance, which combines the Subtractive notion of difference, with -- Basis. -- --
-- distance a b >= zero -- distance a a == zero -- distance a b *| basis (a - b) == a - b --distance :: (Basis a, Subtractive a) => a -> a -> Mag a -- | Convert between a "co-ordinated" or "higher-kinded" number and a -- direction. -- --
-- ray . angle == basis -- magnitude (ray x) == one --class (Distributive coord, Distributive (Dir coord)) => Direction coord where { type Dir coord :: Type; } angle :: Direction coord => coord -> Dir coord ray :: Direction coord => Dir coord -> coord -- | Something that has a magnitude and a direction, with both expressed as -- the same type. -- -- See Polar coordinate system data Polar a Polar :: a -> a -> Polar a [radial] :: Polar a -> a [azimuth] :: Polar a -> a -- | Convert a higher-kinded number that has direction, to a Polar polar :: (Dir (Base a) ~ Mag a, Basis a, Direction (Base a)) => a -> Polar (Mag a) -- | Convert a Polar to a (higher-kinded) number that has a direction. coord :: (Scalar m ~ Dir m, MultiplicativeAction m, Direction m) => Polar (Scalar m) -> m -- | A small number, especially useful for approximate equality. class (Eq a, Additive a) => Epsilon a epsilon :: Epsilon a => a -- | Approximate equality -- --
-- >>> aboutEqual zero (epsilon :: Double) -- True --aboutEqual :: (Epsilon a, Lattice a, Subtractive a) => a -> a -> Bool -- | Note that the constraint is Lattice rather than Ord allowing broader -- usage. -- --
-- >>> nearZero (epsilon :: Double) -- True ---- --
-- >>> nearZero (epsilon :: EuclideanPair Double) -- True --nearZero :: (Epsilon a, Lattice a, Subtractive a) => a -> Bool -- | About equal operator. -- --
-- >>> (1.0 + epsilon) ~= (1.0 :: Double) -- True --(~=) :: Epsilon a => (Lattice a, Subtractive a) => a -> a -> Bool infixl 4 ~= -- | The underlying representation is a newtype-wrapped tuple, compared -- with the base datatype. This was chosen to facilitate the use of -- DerivingVia. newtype Complex a Complex :: (a, a) -> Complex a [complexPair] :: Complex a -> (a, a) -- | Complex number constructor. (+:) :: a -> a -> Complex a infixl 6 +: -- | Extracts the real part of a complex number. realPart :: Complex a -> a -- | Extracts the imaginary part of a complex number. imagPart :: Complex a -> a -- | An Integral is anything that satisfies the law: -- --
-- \a b -> b == zero || b * (a `div` b) + (a `mod` b) == a ---- --
-- >>> 3 `divMod` 2 -- (1,1) ---- --
-- >>> (-3) `divMod` 2 -- (-2,1) ---- --
-- >>> (-3) `quotRem` 2 -- (-1,-1) --class (Distributive a) => Integral a div :: Integral a => a -> a -> a mod :: Integral a => a -> a -> a divMod :: Integral a => a -> a -> (a, a) quot :: Integral a => a -> a -> a rem :: Integral a => a -> a -> a quotRem :: Integral a => a -> a -> (a, a) infixl 7 `div` infixl 7 `mod` -- | toIntegral is kept separate from Integral to help with compatability -- issues. -- --
-- toIntegral a == a --class ToIntegral a b toIntegral :: ToIntegral a b => a -> b -- | Convert to an Int type ToInt a = ToIntegral a Int -- | Polymorphic version of fromInteger -- --
-- fromIntegral a == a --class FromIntegral a b fromIntegral :: FromIntegral a b => b -> a -- | fromInteger is special in two ways: -- --
-- >>> even 2 -- True --even :: (Eq a, Integral a) => a -> Bool -- |
-- >>> odd 3 -- True --odd :: (Eq a, Integral a) => a -> Bool -- | raise a number to an Integral power -- --
-- >>> 2 ^^ 3 -- 8.0 ---- --
-- >>> 2 ^^ (-2) -- 0.25 --(^^) :: (Ord b, Divisive a, Subtractive b, Integral b) => a -> b -> a infixr 8 ^^ -- | raise a number to an Int power -- -- Note: This differs from (^) found in prelude which is a partial -- function (it errors on negative integrals). This is a monomorphic -- version of (^^) provided to help reduce ambiguous type noise in -- common usages. -- --
-- >>> 2 ^ 3 -- 8.0 ---- --
-- >>> 2 ^ (-2) -- 0.25 --(^) :: Divisive a => a -> Int -> a infixr 8 ^ -- | A rational number, represented as the ratio of two Integral -- numbers. data Ratio a (:%) :: !a -> !a -> Ratio a -- | Ratio of two integers type Rational = Ratio Integer -- | toRatio is equivalent to Real in base, but is polymorphic in -- the Integral type. -- --
-- >>> toRatio (3.1415927 :: Float) :: Ratio Integer -- 13176795 :% 4194304 --class ToRatio a b toRatio :: ToRatio a b => a -> Ratio b -- | Fractional in base splits into fromRatio and Field -- --
-- >>> fromRatio (5 :% 2 :: Ratio Integer) :: Double -- 2.5 --class FromRatio a b fromRatio :: FromRatio a b => Ratio b -> a -- | fromRational is special in two ways: -- --
-- >>> reduce 72 60 -- 6 :% 5 ---- --
-- \a b -> reduce a b == a :% b || b == zero --reduce :: (Eq a, Subtractive a, EndoBased a, Integral a) => a -> a -> Ratio a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. -- --
-- >>> gcd 72 60 -- 12 --gcd :: (Eq a, EndoBased a, Integral a) => a -> a -> a -- | A numhask exception. newtype NumHaskException NumHaskException :: String -> NumHaskException [errorMessage] :: NumHaskException -> String -- | Throw an exception. Exceptions may be thrown from purely functional -- code, but may only be caught within the IO monad. -- -- WARNING: You may want to use throwIO instead so that your -- pure code stays exception-free. throw :: forall (r :: RuntimeRep) (a :: TYPE r) e. Exception e => e -> a -- | A prelude composed by overlaying numhask on Prelude, together with a -- few minor tweaks needed for RebindableSyntax. module NumHask.Prelude -- | RebindableSyntax splats this, and I'm not sure where it exists in GHC -- land ifThenElse :: Bool -> a -> a -> a -- | The fromList function constructs the structure l from -- the given list of Item l fromList :: IsList l => [Item l] -> l -- | The fromListN function takes the input list's length and -- potentially uses it to construct the structure l more -- efficiently compared to fromList. If the given number does not -- equal to the input list's length the behaviour of fromListN is -- not specified. -- --
-- fromListN (length xs) xs == fromList xs --fromListN :: IsList l => Int -> [Item l] -> l -- | Natural number -- -- Invariant: numbers <= 0xffffffffffffffff use the NS -- constructor data () => Natural pattern NatJ# :: BigNat -> Natural pattern NatS# :: Word# -> Natural -- | Boolean monoid under disjunction (||). -- --
-- >>> getAny (Any True <> mempty <> Any False) -- True ---- --
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True --newtype () => Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- -- -- You can alternatively define sconcat instead of -- (<>), in which case the laws are: -- --
-- >>> [1,2,3] <> [4,5,6] -- [1,2,3,4,5,6] --(<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. -- --
-- >>> import Data.List.NonEmpty (NonEmpty (..)) -- -- >>> sconcat $ "Hello" :| [" ", "Haskell", "!"] -- "Hello Haskell!" --sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in <math> by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. -- --
-- >>> stimes 4 [1] -- [1,1,1,1] --stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | Beware that Data.Semigroup.Last is different from -- Data.Monoid.Last. The former simply returns the last -- value, so x <> Data.Semigroup.Last Nothing = -- Data.Semigroup.Last Nothing. The latter returns the last -- non-Nothing, thus x <> Data.Monoid.Last Nothing = -- x. newtype () => Last a Last :: a -> Last a [getLast] :: Last a -> a -- | Beware that Data.Semigroup.First is different from -- Data.Monoid.First. The former simply returns the first -- value, so Data.Semigroup.First Nothing <> x = -- Data.Semigroup.First Nothing. The latter returns the first -- non-Nothing, thus Data.Monoid.First Nothing <> x = -- x. newtype () => First a First :: a -> First a [getFirst] :: First a -> a -- | Boolean monoid under conjunction (&&). -- --
-- >>> getAll (All True <> mempty <> All False) -- False ---- --
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False --newtype () => All All :: Bool -> All [getAll] :: All -> Bool -- | The monoid of endomorphisms under composition. -- --
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
--
newtype () => Endo a
Endo :: (a -> a) -> Endo a
[appEndo] :: Endo a -> a -> a
-- | The dual of a Monoid, obtained by swapping the arguments of
-- mappend.
--
-- -- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" --newtype () => Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. newtype () => WrappedMonoid m WrapMonoid :: m -> WrappedMonoid m [unwrapMonoid] :: WrappedMonoid m -> m -- |
-- >>> Max (Arg 0 ()) <> Max (Arg 1 ())
-- Max {getMax = Arg 1 ()}
--
type ArgMax a b = Max Arg a b
-- |
-- >>> Min (Arg 0 ()) <> Min (Arg 1 ())
-- Min {getMin = Arg 0 ()}
--
type ArgMin a b = Min Arg a b
-- | Arg isn't itself a Semigroup in its own right, but it
-- can be placed inside Min and Max to compute an arg min
-- or arg max.
--
-- -- >>> minimum [ Arg (x * x) x | x <- [-10 .. 10] ] -- Arg 0 0 --data () => Arg a b Arg :: a -> b -> Arg a b -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in <math> rather than <math>. stimesIdempotent :: Integral b => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in <math> rather than <math> stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | This lets you use a difference list of a Semigroup as a -- Monoid. -- --
-- >>> let hello = diff "Hello, " -- -- >>> appEndo hello "World!" -- "Hello, World!" -- -- >>> appEndo (hello <> mempty) "World!" -- "Hello, World!" -- -- >>> appEndo (mempty <> hello) "World!" -- "Hello, World!" -- -- >>> let world = diff "World" -- -- >>> let excl = diff "!" -- -- >>> appEndo (hello <> (world <> excl)) mempty -- "Hello, World!" -- -- >>> appEndo ((hello <> world) <> excl) mempty -- "Hello, World!" --diff :: Semigroup m => m -> Endo m -- | Repeat a value n times. -- --
-- mtimesDefault n a = a <> a <> ... <> a -- using <> (n-1) times ---- -- In many cases, `stimes 0 a` for a Monoid will produce -- mempty. However, there are situations when it cannot do so. In -- particular, the following situation is fairly common: -- --
-- data T a = ... -- -- class Constraint1 a -- class Constraint1 a => Constraint2 a ---- -- instance Constraint1 a => Semigroup (T a) instance -- Constraint2 a => Monoid (T a) @ -- -- Since Constraint1 is insufficient to implement mempty, -- stimes for T a cannot do so. -- -- When working with such a type, or when working polymorphically with -- Semigroup instances, mtimesDefault should be used when -- the multiplier might be zero. It is implemented using stimes -- when the multiplier is nonzero and mempty when it is zero. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is representation-polymorphic in its -- result type, so that foo $ True where foo :: Bool -- -> Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | const x y always evaluates to x, ignoring its second -- argument. -- --
-- >>> const 42 "hello" -- 42 ---- --
-- >>> map (const 42) [0..3] -- [42,42,42,42] --const :: a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
-- >>> flip (++) "hello" "world" -- "worldhello" --flip :: (a -> b -> c) -> b -> a -> c -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
-- >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5 -- 120 ---- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
-- >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5 -- 120 ---- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix’s argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
-- ((+) `on` f) x y = f x + f y ---- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- --
(*) `on` id = (*) -- (if (*) ∉ {⊥, const -- ⊥})
((*) `on` f) `on` g = (*) `on` (f . g)
flip on f . flip on g = flip on (g . -- f)
-- >>> 5 & (+1) & show -- "6" --(&) :: a -> (a -> b) -> b infixl 1 & -- | applyWhen applies a function to a value if a condition is true, -- otherwise, it returns the value unchanged. -- -- It is equivalent to flip (bool id). -- -- Algebraic properties: -- -- applyWhen :: Bool -> (a -> a) -> a -> a -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
-- {-# LANGUAGE DeriveFoldable #-}
-- data Tree a = Empty
-- | Leaf a
-- | Node (Tree a) a (Tree a)
-- deriving Foldable
--
--
-- A more detailed description can be found in the Overview
-- section of Data.Foldable#overview.
--
-- For the class laws see the Laws section of
-- Data.Foldable#laws.
class () => Foldable (t :: Type -> Type)
-- | Given a structure with elements whose type is a Monoid, combine
-- them via the monoid's (<>) operator. This fold
-- is right-associative and lazy in the accumulator. When you need a
-- strict left-associative fold, use foldMap' instead, with
-- id as the map.
--
-- -- >>> fold [[1, 2, 3], [4, 5], [6], []] -- [1,2,3,4,5,6] ---- --
-- >>> fold $ Node (Leaf (Sum 1)) (Sum 3) (Leaf (Sum 5))
-- Sum {getSum = 9}
--
--
-- Folds of unbounded structures do not terminate when the monoid's
-- (<>) operator is strict:
--
-- -- >>> fold (repeat Nothing) -- * Hangs forever * ---- -- Lazy corecursive folds of unbounded structures are fine: -- --
-- >>> take 12 $ fold $ map (\i -> [i..i+2]) [0..] -- [0,1,2,1,2,3,2,3,4,3,4,5] -- -- >>> sum $ take 4000000 $ fold $ map (\i -> [i..i+2]) [0..] -- 2666668666666 --fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure into a monoid, and combine the -- results with (<>). This fold is -- right-associative and lazy in the accumulator. For strict -- left-associative folds consider foldMap' instead. -- --
-- >>> foldMap Sum [1, 3, 5]
-- Sum {getSum = 9}
--
--
--
-- >>> foldMap Product [1, 3, 5]
-- Product {getProduct = 15}
--
--
-- -- >>> foldMap (replicate 3) [1, 2, 3] -- [1,1,1,2,2,2,3,3,3] ---- -- When a Monoid's (<>) is lazy in its second -- argument, foldMap can return a result even from an unbounded -- structure. For example, lazy accumulation enables -- Data.ByteString.Builder to efficiently serialise large data -- structures and produce the output incrementally: -- --
-- >>> import qualified Data.ByteString.Lazy as L -- -- >>> import qualified Data.ByteString.Builder as B -- -- >>> let bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20 -- -- >>> let lbs = B.toLazyByteString $ foldMap bld [0..] -- -- >>> L.take 64 lbs -- "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24" --foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | A left-associative variant of foldMap that is strict in the -- accumulator. Use this method for strict reduction when partial results -- are merged via (<>). -- --
-- >>> :set -XGeneralizedNewtypeDeriving -- -- >>> import Data.Bits (Bits, FiniteBits, xor, zeroBits) -- -- >>> import Data.Foldable (foldMap') -- -- >>> import Numeric (showHex) -- -- >>> -- -- >>> newtype X a = X a deriving (Eq, Bounded, Enum, Bits, FiniteBits) -- -- >>> instance Bits a => Semigroup (X a) where X a <> X b = X (a `xor` b) -- -- >>> instance Bits a => Monoid (X a) where mempty = X zeroBits -- -- >>> -- -- >>> let bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411] -- -- >>> (\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits -- "0x42" --foldMap' :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | Right-associative fold of a structure, lazy in the accumulator. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that since the head of the resulting expression is produced by an -- application of the operator to the first element of the list, given an -- operator lazy in its right argument, foldr can produce a -- terminating expression from an unbounded list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList ---- --
-- >>> foldr (||) False [False, True, False] -- True ---- --
-- >>> foldr (||) False [] -- False ---- --
-- >>> foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd'] -- "foodcba" ---- --
-- >>> foldr (||) False (True : repeat False) -- True ---- -- But the following doesn't terminate: -- --
-- >>> foldr (||) False (repeat False ++ [True]) -- * Hangs forever * ---- --
-- >>> take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1) -- [1,4,7,10,13] --foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | foldr' is a variant of foldr that performs strict -- reduction from right to left, i.e. starting with the right-most -- element. The input structure must be finite, otherwise -- foldr' runs out of space (diverges). -- -- If you want a strict right fold in constant space, you need a -- structure that supports faster than O(n) access to the -- right-most element, such as Seq from the containers -- package. -- -- This method does not run in constant space for structures such as -- lists that don't support efficient right-to-left iteration and so -- require O(n) space to perform right-to-left reduction. Use of -- this method with such a structure is a hint that the chosen structure -- may be a poor fit for the task at hand. If the order in which the -- elements are combined is not important, use foldl' instead. foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Left-associative fold of a structure, lazy in the accumulator. This is -- rarely what you want, but can work well for structures with efficient -- right-to-left sequencing and an operator that is lazy in its left -- argument. -- -- In the case of lists, foldl, when applied to a binary operator, -- a starting value (typically the left-identity of the operator), and a -- list, reduces the list using the binary operator, from left to right: -- --
-- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn ---- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. Like all left-associative folds, -- foldl will diverge if given an infinite list. -- -- If you want an efficient strict left-fold, you probably want to use -- foldl' instead of foldl. The reason for this is that the -- latter does not force the inner results (e.g. z `f` x1 -- in the above example) before applying them to the operator (e.g. to -- (`f` x2)). This results in a thunk chain O(n) elements -- long, which then must be evaluated from the outside-in. -- -- For a general Foldable structure this should be semantically -- identical to: -- --
-- foldl f z = foldl f z . toList ---- --
-- >>> foldl (+) 42 [1,2,3,4] -- 52 ---- -- Though the result below is lazy, the input is reversed before -- prepending it to the initial accumulator, so corecursion begins only -- after traversing the entire input string. -- --
-- >>> foldl (\acc c -> c : acc) "abcd" "efgh" -- "hgfeabcd" ---- -- A left fold of a structure that is infinite on the right cannot -- terminate, even when for any finite input the fold just returns the -- initial accumulator: -- --
-- >>> foldl (\a _ -> a) 0 $ repeat 1 -- * Hangs forever * ---- -- WARNING: When it comes to lists, you always want to use either -- foldl' or foldr instead. foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to Weak Head Normal -- Form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite structure to a single strict result (e.g. sum). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl' f z = foldl' f z . toList --foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | A variant of foldr that has no base case, and thus may only be -- applied to non-empty structures. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. -- --
-- >>> foldr1 (+) [1..4] -- 10 ---- --
-- >>> foldr1 (+) [] -- Exception: Prelude.foldr1: empty list ---- --
-- >>> foldr1 (+) Nothing -- *** Exception: foldr1: empty structure ---- --
-- >>> foldr1 (-) [1..4] -- -2 ---- --
-- >>> foldr1 (&&) [True, False, True, True] -- False ---- --
-- >>> foldr1 (||) [False, False, True, True] -- True ---- --
-- >>> foldr1 (+) [1..] -- * Hangs forever * --foldr1 :: Foldable t => (a -> a -> a) -> t a -> a -- | A variant of foldl that has no base case, and thus may only be -- applied to non-empty structures. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. -- --
-- foldl1 f = foldl1 f . toList ---- --
-- >>> foldl1 (+) [1..4] -- 10 ---- --
-- >>> foldl1 (+) [] -- *** Exception: Prelude.foldl1: empty list ---- --
-- >>> foldl1 (+) Nothing -- *** Exception: foldl1: empty structure ---- --
-- >>> foldl1 (-) [1..4] -- -8 ---- --
-- >>> foldl1 (&&) [True, False, True, True] -- False ---- --
-- >>> foldl1 (||) [False, False, True, True] -- True ---- --
-- >>> foldl1 (+) [1..] -- * Hangs forever * --foldl1 :: Foldable t => (a -> a -> a) -> t a -> a -- | List of elements of a structure, from left to right. If the entire -- list is intended to be reduced via a fold, just fold the structure -- directly bypassing the list. -- --
-- >>> toList Nothing -- [] ---- --
-- >>> toList (Just 42) -- [42] ---- --
-- >>> toList (Left "foo") -- [] ---- --
-- >>> toList (Node (Leaf 5) 17 (Node Empty 12 (Leaf 8))) -- [5,17,12,8] ---- -- For lists, toList is the identity: -- --
-- >>> toList [1, 2, 3] -- [1,2,3] --toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- Left-associative and lazy in both the initial element and the -- accumulator. Thus optimised for structures where the first element can -- be accessed in constant time. Structures where this is not the case -- should have a non-default implementation. -- --
-- >>> null [] -- True ---- --
-- >>> null [1] -- False ---- -- null is expected to terminate even for infinite structures. The -- default implementation terminates provided the structure is bounded on -- the left (there is a leftmost element). -- --
-- >>> null [1..] -- False --null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation just counts elements starting with the -- leftmost. Instances for structures that can compute the element count -- faster than via element-by-element counting, should provide a -- specialised implementation. -- --
-- >>> length [] -- 0 ---- --
-- >>> length ['a', 'b', 'c'] -- 3 -- -- >>> length [1..] -- * Hangs forever * --length :: Foldable t => t a -> Int -- | Does the element occur in the structure? -- -- Note: elem is often used in infix form. -- --
-- >>> 3 `elem` [] -- False ---- --
-- >>> 3 `elem` [1,2] -- False ---- --
-- >>> 3 `elem` [1,2,3,4,5] -- True ---- -- For infinite structures, the default implementation of elem -- terminates if the sought-after value exists at a finite distance from -- the left side of the structure: -- --
-- >>> 3 `elem` [1..] -- True ---- --
-- >>> 3 `elem` ([4..] ++ [3]) -- * Hangs forever * --elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The largest element of a non-empty structure. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. A structure that supports random access -- and maintains its elements in order should provide a specialised -- implementation to return the maximum in faster than linear time. -- --
-- >>> maximum [1..10] -- 10 ---- --
-- >>> maximum [] -- *** Exception: Prelude.maximum: empty list ---- --
-- >>> maximum Nothing -- *** Exception: maximum: empty structure ---- -- WARNING: This function is partial for possibly-empty structures like -- lists. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. A structure that supports random access -- and maintains its elements in order should provide a specialised -- implementation to return the minimum in faster than linear time. -- --
-- >>> minimum [1..10] -- 1 ---- --
-- >>> minimum [] -- *** Exception: Prelude.minimum: empty list ---- --
-- >>> minimum Nothing -- *** Exception: minimum: empty structure ---- -- WARNING: This function is partial for possibly-empty structures like -- lists. minimum :: (Foldable t, Ord a) => t a -> a infix 4 `elem` -- | The largest element of a non-empty structure with respect to the given -- comparison function. -- --
-- >>> maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"] -- "Longest" ---- -- WARNING: This function is partial for possibly-empty structures like -- lists. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. -- --
-- >>> minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"] -- "!" ---- -- WARNING: This function is partial for possibly-empty structures like -- lists. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The concatenation of all the elements of a container of lists. -- --
-- >>> concat (Just [1, 2, 3]) -- [1,2,3] ---- --
-- >>> concat (Left 42) -- [] ---- --
-- >>> concat [[1, 2, 3], [4, 5], [6], []] -- [1,2,3,4,5,6] --concat :: Foldable t => t [a] -> [a] -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. -- --
-- >>> and [] -- True ---- --
-- >>> and [True] -- True ---- --
-- >>> and [False] -- False ---- --
-- >>> and [True, True, False] -- False ---- --
-- >>> and (False : repeat True) -- Infinite list [False,True,True,True,... -- False ---- --
-- >>> and (repeat True) -- * Hangs forever * --and :: Foldable t => t Bool -> Bool -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. -- --
-- >>> or [] -- False ---- --
-- >>> or [True] -- True ---- --
-- >>> or [False] -- False ---- --
-- >>> or [True, True, False] -- True ---- --
-- >>> or (True : repeat False) -- Infinite list [True,False,False,False,... -- True ---- --
-- >>> or (repeat False) -- * Hangs forever * --or :: Foldable t => t Bool -> Bool -- | Determines whether any element of the structure satisfies the -- predicate. -- --
-- >>> any (> 3) [] -- False ---- --
-- >>> any (> 3) [1,2] -- False ---- --
-- >>> any (> 3) [1,2,3,4,5] -- True ---- --
-- >>> any (> 3) [1..] -- True ---- --
-- >>> any (> 3) [0, -1..] -- * Hangs forever * --any :: Foldable t => (a -> Bool) -> t a -> Bool -- | Determines whether all elements of the structure satisfy the -- predicate. -- --
-- >>> all (> 3) [] -- True ---- --
-- >>> all (> 3) [1,2] -- False ---- --
-- >>> all (> 3) [1,2,3,4,5] -- False ---- --
-- >>> all (> 3) [1..] -- False ---- --
-- >>> all (> 3) [4..] -- * Hangs forever * --all :: Foldable t => (a -> Bool) -> t a -> Bool -- | notElem is the negation of elem. -- --
-- >>> 3 `notElem` [] -- True ---- --
-- >>> 3 `notElem` [1,2] -- True ---- --
-- >>> 3 `notElem` [1,2,3,4,5] -- False ---- -- For infinite structures, notElem terminates if the value exists -- at a finite distance from the left side of the structure: -- --
-- >>> 3 `notElem` [1..] -- False ---- --
-- >>> 3 `notElem` ([4..] ++ [3]) -- * Hangs forever * --notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | Map a function over all the elements of a container and concatenate -- the resulting lists. -- --
-- >>> concatMap (take 3) [[1..], [10..], [100..], [1000..]] -- [1,2,3,10,11,12,100,101,102,1000,1001,1002] ---- --
-- >>> concatMap (take 3) (Just [1..]) -- [1,2,3] --concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | Right-to-left monadic fold over the elements of a structure. -- -- Given a structure t with elements (a, b, c, ..., x, -- y), the result of a fold with an operator function f is -- equivalent to: -- --
-- foldrM f z t = do -- yy <- f y z -- xx <- f x yy -- ... -- bb <- f b cc -- aa <- f a bb -- return aa -- Just @return z@ when the structure is empty ---- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
-- (f1 >=> f2) a = f1 a >>= f2 ---- -- Another way of thinking about foldrM is that it amounts to an -- application to z of a Kleisli composition: -- --
-- foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ z ---- -- The monadic effects of foldrM are sequenced from right to -- left, and e.g. folds of infinite lists will diverge. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from a tail of the element sequence. If -- you want to evaluate the monadic effects in left-to-right order, or -- perhaps be able to short-circuit after an initial sequence of -- elements, you'll need to use foldlM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the leftmost element a, so that, ignoring -- effects, the result looks like a right fold: -- --
-- a `f` (b `f` (c `f` (... (x `f` (y `f` z))))). ---- --
-- >>> let f i acc = do { print i ; return $ i : acc }
--
-- >>> foldrM f [] [0..3]
-- 3
-- 2
-- 1
-- 0
-- [0,1,2,3]
--
foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
-- | Left-to-right monadic fold over the elements of a structure.
--
-- Given a structure t with elements (a, b, ..., w, x,
-- y), the result of a fold with an operator function f is
-- equivalent to:
--
-- -- foldlM f z t = do -- aa <- f z a -- bb <- f aa b -- ... -- xx <- f ww x -- yy <- f xx y -- return yy -- Just @return z@ when the structure is empty ---- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
-- (f1 >=> f2) a = f1 a >>= f2 ---- -- Another way of thinking about foldlM is that it amounts to an -- application to z of a Kleisli composition: -- --
-- foldlM f z t = -- flip f a >=> flip f b >=> ... >=> flip f x >=> flip f y $ z ---- -- The monadic effects of foldlM are sequenced from left to -- right. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from an initial segment of the element -- sequence. If you want to evaluate the monadic effects in right-to-left -- order, or perhaps be able to short-circuit after processing a tail of -- the sequence of elements, you'll need to use foldrM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the rightmost element y, so that, -- ignoring effects, the result looks like a left fold: -- --
-- ((((z `f` a) `f` b) ... `f` w) `f` x) `f` y ---- --
-- >>> let f a e = do { print e ; return $ e : a }
--
-- >>> foldlM f [] [0..3]
-- 0
-- 1
-- 2
-- 3
-- [3,2,1,0]
--
foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
-- | Map each element of a structure to an Applicative action,
-- evaluate these actions from left to right, and ignore the results. For
-- a version that doesn't ignore the results see traverse.
--
-- traverse_ is just like mapM_, but generalised to
-- Applicative actions.
--
-- -- >>> traverse_ print ["Hello", "world", "!"] -- "Hello" -- "world" -- "!" --traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. This is -- forM_ generalised to Applicative actions. -- -- for_ is just like forM_, but generalised to -- Applicative actions. -- --
-- >>> for_ [1..4] print -- 1 -- 2 -- 3 -- 4 --for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and ignore the results. For a version that -- doesn't ignore the results see mapM. -- -- mapM_ is just like traverse_, but specialised to monadic -- actions. mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () -- | forM_ is mapM_ with its arguments flipped. For a version -- that doesn't ignore the results see forM. -- -- forM_ is just like for_, but specialised to monadic -- actions. forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m () -- | Evaluate each action in the structure from left to right, and ignore -- the results. For a version that doesn't ignore the results see -- sequenceA. -- -- sequenceA_ is just like sequence_, but generalised to -- Applicative actions. -- --
-- >>> sequenceA_ [print "Hello", print "world", print "!"] -- "Hello" -- "world" -- "!" --sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f () -- | Evaluate each monadic action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results see -- sequence. -- -- sequence_ is just like sequenceA_, but specialised to -- monadic actions. sequence_ :: (Foldable t, Monad m) => t (m a) -> m () -- | The sum of a collection of actions using (<|>), -- generalizing concat. -- -- asum is just like msum, but generalised to -- Alternative. -- --
-- >>> asum [Just "Hello", Nothing, Just "World"] -- Just "Hello" --asum :: (Foldable t, Alternative f) => t (f a) -> f a -- | The sum of a collection of actions using (<|>), -- generalizing concat. -- -- msum is just like asum, but specialised to -- MonadPlus. -- --
-- >>> msum [Just "Hello", Nothing, Just "World"] -- Just "Hello" --msum :: (Foldable t, MonadPlus m) => t (m a) -> m a -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. -- --
-- >>> find (> 42) [0, 5..] -- Just 45 ---- --
-- >>> find (> 12) [1..7] -- Nothing --find :: Foldable t => (a -> Bool) -> t a -> Maybe a -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data () => Int -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise Integer and IN constructors are used -- to store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: Integer and IN are used iff value doesn't fit -- in IS data () => Integer -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data () => Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data () => Float -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Show is equivalent to -- --
-- instance (Show a) => Show (Tree a) where -- -- showsPrec d (Leaf m) = showParen (d > app_prec) $ -- showString "Leaf " . showsPrec (app_prec+1) m -- where app_prec = 10 -- -- showsPrec d (u :^: v) = showParen (d > up_prec) $ -- showsPrec (up_prec+1) u . -- showString " :^: " . -- showsPrec (up_prec+1) v -- where up_prec = 5 ---- -- Note that right-associativity of :^: is ignored. For example, -- --
-- showsPrec d x r ++ s == showsPrec d x (r ++ s) ---- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. showsPrec :: Show a => Int -> a -> ShowS -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | The method showList is provided to allow the programmer to give -- a specialised way of showing lists of values. For example, this is -- used by the predefined Show instance of the Char type, -- where values of type String should be shown in double quotes, -- rather than between square brackets. showList :: Show a => [a] -> ShowS -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class () => Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- --
-- enumFrom x = enumFromTo x maxBound -- enumFromThen x y = enumFromThenTo x y bound -- where -- bound | fromEnum y >= fromEnum x = maxBound -- | otherwise = minBound --class () => Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- --
enumFrom 4 :: [Integer] = [4,5,6,7,...]
enumFrom 6 :: [Int] = [6,7,8,9,...,maxBound :: -- Int]
enumFromThen 4 6 :: [Integer] = [4,6,8,10...]
enumFromThen 6 2 :: [Int] = [6,2,-2,-6,...,minBound :: -- Int]
enumFromTo 6 10 :: [Int] = [6,7,8,9,10]
enumFromTo 42 1 :: [Integer] = []
enumFromThenTo 4 2 -6 :: [Integer] = -- [4,2,0,-2,-4,-6]
enumFromThenTo 6 8 2 :: [Int] = []
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
-- instance (Read a) => Read (Tree a) where
--
-- readsPrec d r = readParen (d > app_prec)
-- (\r -> [(Leaf m,t) |
-- ("Leaf",s) <- lex r,
-- (m,t) <- readsPrec (app_prec+1) s]) r
--
-- ++ readParen (d > up_prec)
-- (\r -> [(u:^:v,w) |
-- (u,s) <- readsPrec (up_prec+1) r,
-- (":^:",t) <- lex s,
-- (v,w) <- readsPrec (up_prec+1) t]) r
--
-- where app_prec = 10
-- up_prec = 5
--
--
-- Note that right-associativity of :^: is unused.
--
-- The derived instance in GHC is equivalent to
--
-- -- instance (Read a) => Read (Tree a) where -- -- readPrec = parens $ (prec app_prec $ do -- Ident "Leaf" <- lexP -- m <- step readPrec -- return (Leaf m)) -- -- +++ (prec up_prec $ do -- u <- step readPrec -- Symbol ":^:" <- lexP -- v <- step readPrec -- return (u :^: v)) -- -- where app_prec = 10 -- up_prec = 5 -- -- readListPrec = readListPrecDefault ---- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
-- instance Read T where -- readPrec = ... -- readListPrec = readListPrecDefault --class () => Read a -- | attempts to parse a value from the front of the string, returning a -- list of (parsed value, remaining string) pairs. If there is no -- successful parse, the returned list is empty. -- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. readsPrec :: Read a => Int -> ReadS a -- | The method readList is provided to allow the programmer to give -- a specialised way of parsing lists of values. For example, this is -- used by the predefined Read instance of the Char type, -- where values of type String should be are expected to use -- double quotes, rather than square brackets. readList :: Read a => ReadS [a] -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data () => IO a -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- Ord, as defined by the Haskell report, implements a total order -- and has the following properties: -- --
-- >>> "Hello world" <> mempty -- "Hello world" --mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. Should it be implemented manually, since -- mappend is a synonym for (<>), it is expected that -- the two functions are defined the same way. In a future GHC release -- mappend will be removed from Monoid. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. -- --
-- >>> mconcat ["Hello", " ", "Haskell", "!"] -- "Hello Haskell!" --mconcat :: Monoid a => [a] -> a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- -- -- You can alternatively define sconcat instead of -- (<>), in which case the laws are: -- --
-- >>> [1,2,3] <> [4,5,6] -- [1,2,3,4,5,6] --(<>) :: Semigroup a => a -> a -> a infixr 6 <> -- | A functor with application, providing operations to -- --
-- (<*>) = liftA2 id ---- --
-- liftA2 f x y = f <$> x <*> y ---- -- Further, any definition must satisfy the following: -- --
pure id <*> v = -- v
pure (.) <*> u -- <*> v <*> w = u <*> (v -- <*> w)
pure f <*> -- pure x = pure (f x)
u <*> pure y = -- pure ($ y) <*> u
-- forall x y. p (q x y) = f x . g y ---- -- it follows from the above that -- --
-- liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v ---- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. -- --
-- >>> data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
--
--
-- -- >>> produceFoo :: Applicative f => f Foo ---- --
-- >>> produceBar :: Applicative f => f Bar -- -- >>> produceBaz :: Applicative f => f Baz ---- --
-- >>> mkState :: Applicative f => f MyState -- -- >>> mkState = MyState <$> produceFoo <*> produceBar <*> produceBaz --(<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. -- -- This became a typeclass method in 4.10.0.0. Prior to that, it was a -- function defined in terms of <*> and fmap. -- --
-- >>> liftA2 (,) (Just 3) (Just 5) -- Just (3,5) --liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. -- --
-- >>> Just 2 *> Just 3 -- Just 3 ---- --
-- >>> Nothing *> Just 3 -- Nothing ---- -- Of course a more interesting use case would be to have effectful -- computations instead of just returning pure values. -- --
-- >>> import Data.Char
--
-- >>> import Text.ParserCombinators.ReadP
--
-- >>> let p = string "my name is " *> munch1 isAlpha <* eof
--
-- >>> readP_to_S p "my name is Simon"
-- [("Simon","")]
--
(*>) :: Applicative f => f a -> f b -> f b
-- | Sequence actions, discarding the value of the second argument.
(<*) :: Applicative f => f a -> f b -> f a
infixl 4 <*>
infixl 4 *>
infixl 4 <*
-- | A type f is a Functor if it provides a function fmap
-- which, given any types a and b lets you apply any
-- function from (a -> b) to turn an f a into an
-- f b, preserving the structure of f. Furthermore
-- f needs to adhere to the following:
--
--
--
-- Note, that the second law follows from the free theorem of the type
-- fmap and the first law, so you need only check that the former
-- condition holds. See
-- https://www.schoolofhaskell.com/user/edwardk/snippets/fmap or
-- https://github.com/quchen/articles/blob/master/second_functor_law.md
-- for an explanation.
class () => Functor (f :: Type -> Type)
-- | fmap is used to apply a function of type (a -> b)
-- to a value of type f a, where f is a functor, to produce a
-- value of type f b. Note that for any type constructor with
-- more than one parameter (e.g., Either), only the last type
-- parameter can be modified with fmap (e.g., b in
-- `Either a b`).
--
-- Some type constructors with two parameters or more have a
-- Bifunctor instance that allows both the last and the
-- penultimate parameters to be mapped over.
--
-- -- >>> fmap show Nothing -- Nothing -- -- >>> fmap show (Just 3) -- Just "3" ---- -- Convert from an Either Int Int to an Either Int -- String using show: -- --
-- >>> fmap show (Left 17) -- Left 17 -- -- >>> fmap show (Right 17) -- Right "17" ---- -- Double each element of a list: -- --
-- >>> fmap (*2) [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> fmap even (2,2) -- (2,True) ---- -- It may seem surprising that the function is only applied to the last -- element of the tuple compared to the list example above which applies -- it to every element in the list. To understand, remember that tuples -- are type constructors with multiple type parameters: a tuple of 3 -- elements (a,b,c) can also be written (,,) a b c and -- its Functor instance is defined for Functor ((,,) a -- b) (i.e., only the third parameter is free to be mapped over with -- fmap). -- -- It explains why fmap can be used with tuples containing -- values of different types as in the following example: -- --
-- >>> fmap even ("hello", 1.0, 4)
-- ("hello",1.0,True)
--
fmap :: Functor f => (a -> b) -> f a -> f b
-- | Replace all locations in the input with the same value. The default
-- definition is fmap . const, but this may be
-- overridden with a more efficient version.
--
-- -- >>> 'a' <$ Just 2 -- Just 'a' -- -- >>> 'a' <$ Nothing -- Nothing --(<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- --
-- do a <- as -- bs a --(>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. -- -- 'as >> bs' can be understood as the do -- expression -- --
-- do as -- bs --(>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> s -- Left "foo" -- -- >>> let n = Right 3 :: Either String Int -- -- >>> n -- Right 3 -- -- >>> :type s -- s :: Either String Int -- -- >>> :type n -- n :: Either String Int ---- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> fmap (*2) s -- Left "foo" -- -- >>> fmap (*2) n -- Right 6 ---- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
-- >>> import Data.Char ( digitToInt, isDigit )
--
-- >>> :{
-- let parseEither :: Char -> Either String Int
-- parseEither c
-- | isDigit c = Right (digitToInt c)
-- | otherwise = Left "parse error"
--
-- >>> :}
--
--
-- The following should work, since both '1' and '2'
-- can be parsed as Ints.
--
--
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither '1'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Right 3 ---- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither 'm'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Left "parse error" --data () => Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The Haskell 2010 type for exceptions in the IO monad. Any I/O -- operation may raise an IOException instead of returning a -- result. For a more general type of exception, including also those -- that arise in pure code, see Exception. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- (+), (*) and exp are -- customarily expected to define an exponential field and have the -- following properties: -- --
-- fail s >>= f = fail s ---- -- If your Monad is also MonadPlus, a popular definition is -- --
-- fail _ = mzero ---- -- fail s should be an action that runs in the monad itself, not -- an exception (except in instances of MonadIO). In particular, -- fail should not be implemented in terms of error. class Monad m => MonadFail (m :: Type -> Type) fail :: MonadFail m => String -> m a -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
-- {-# LANGUAGE DeriveFoldable #-}
-- data Tree a = Empty
-- | Leaf a
-- | Node (Tree a) a (Tree a)
-- deriving Foldable
--
--
-- A more detailed description can be found in the Overview
-- section of Data.Foldable#overview.
--
-- For the class laws see the Laws section of
-- Data.Foldable#laws.
class () => Foldable (t :: Type -> Type)
-- | Map each element of the structure into a monoid, and combine the
-- results with (<>). This fold is
-- right-associative and lazy in the accumulator. For strict
-- left-associative folds consider foldMap' instead.
--
--
-- >>> foldMap Sum [1, 3, 5]
-- Sum {getSum = 9}
--
--
--
-- >>> foldMap Product [1, 3, 5]
-- Product {getProduct = 15}
--
--
-- -- >>> foldMap (replicate 3) [1, 2, 3] -- [1,1,1,2,2,2,3,3,3] ---- -- When a Monoid's (<>) is lazy in its second -- argument, foldMap can return a result even from an unbounded -- structure. For example, lazy accumulation enables -- Data.ByteString.Builder to efficiently serialise large data -- structures and produce the output incrementally: -- --
-- >>> import qualified Data.ByteString.Lazy as L -- -- >>> import qualified Data.ByteString.Builder as B -- -- >>> let bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20 -- -- >>> let lbs = B.toLazyByteString $ foldMap bld [0..] -- -- >>> L.take 64 lbs -- "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24" --foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | Right-associative fold of a structure, lazy in the accumulator. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that since the head of the resulting expression is produced by an -- application of the operator to the first element of the list, given an -- operator lazy in its right argument, foldr can produce a -- terminating expression from an unbounded list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList ---- --
-- >>> foldr (||) False [False, True, False] -- True ---- --
-- >>> foldr (||) False [] -- False ---- --
-- >>> foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd'] -- "foodcba" ---- --
-- >>> foldr (||) False (True : repeat False) -- True ---- -- But the following doesn't terminate: -- --
-- >>> foldr (||) False (repeat False ++ [True]) -- * Hangs forever * ---- --
-- >>> take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1) -- [1,4,7,10,13] --foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Left-associative fold of a structure, lazy in the accumulator. This is -- rarely what you want, but can work well for structures with efficient -- right-to-left sequencing and an operator that is lazy in its left -- argument. -- -- In the case of lists, foldl, when applied to a binary operator, -- a starting value (typically the left-identity of the operator), and a -- list, reduces the list using the binary operator, from left to right: -- --
-- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn ---- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. Like all left-associative folds, -- foldl will diverge if given an infinite list. -- -- If you want an efficient strict left-fold, you probably want to use -- foldl' instead of foldl. The reason for this is that the -- latter does not force the inner results (e.g. z `f` x1 -- in the above example) before applying them to the operator (e.g. to -- (`f` x2)). This results in a thunk chain O(n) elements -- long, which then must be evaluated from the outside-in. -- -- For a general Foldable structure this should be semantically -- identical to: -- --
-- foldl f z = foldl f z . toList ---- --
-- >>> foldl (+) 42 [1,2,3,4] -- 52 ---- -- Though the result below is lazy, the input is reversed before -- prepending it to the initial accumulator, so corecursion begins only -- after traversing the entire input string. -- --
-- >>> foldl (\acc c -> c : acc) "abcd" "efgh" -- "hgfeabcd" ---- -- A left fold of a structure that is infinite on the right cannot -- terminate, even when for any finite input the fold just returns the -- initial accumulator: -- --
-- >>> foldl (\a _ -> a) 0 $ repeat 1 -- * Hangs forever * ---- -- WARNING: When it comes to lists, you always want to use either -- foldl' or foldr instead. foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | A variant of foldr that has no base case, and thus may only be -- applied to non-empty structures. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. -- --
-- >>> foldr1 (+) [1..4] -- 10 ---- --
-- >>> foldr1 (+) [] -- Exception: Prelude.foldr1: empty list ---- --
-- >>> foldr1 (+) Nothing -- *** Exception: foldr1: empty structure ---- --
-- >>> foldr1 (-) [1..4] -- -2 ---- --
-- >>> foldr1 (&&) [True, False, True, True] -- False ---- --
-- >>> foldr1 (||) [False, False, True, True] -- True ---- --
-- >>> foldr1 (+) [1..] -- * Hangs forever * --foldr1 :: Foldable t => (a -> a -> a) -> t a -> a -- | A variant of foldl that has no base case, and thus may only be -- applied to non-empty structures. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. -- --
-- foldl1 f = foldl1 f . toList ---- --
-- >>> foldl1 (+) [1..4] -- 10 ---- --
-- >>> foldl1 (+) [] -- *** Exception: Prelude.foldl1: empty list ---- --
-- >>> foldl1 (+) Nothing -- *** Exception: foldl1: empty structure ---- --
-- >>> foldl1 (-) [1..4] -- -8 ---- --
-- >>> foldl1 (&&) [True, False, True, True] -- False ---- --
-- >>> foldl1 (||) [False, False, True, True] -- True ---- --
-- >>> foldl1 (+) [1..] -- * Hangs forever * --foldl1 :: Foldable t => (a -> a -> a) -> t a -> a -- | Test whether the structure is empty. The default implementation is -- Left-associative and lazy in both the initial element and the -- accumulator. Thus optimised for structures where the first element can -- be accessed in constant time. Structures where this is not the case -- should have a non-default implementation. -- --
-- >>> null [] -- True ---- --
-- >>> null [1] -- False ---- -- null is expected to terminate even for infinite structures. The -- default implementation terminates provided the structure is bounded on -- the left (there is a leftmost element). -- --
-- >>> null [1..] -- False --null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation just counts elements starting with the -- leftmost. Instances for structures that can compute the element count -- faster than via element-by-element counting, should provide a -- specialised implementation. -- --
-- >>> length [] -- 0 ---- --
-- >>> length ['a', 'b', 'c'] -- 3 -- -- >>> length [1..] -- * Hangs forever * --length :: Foldable t => t a -> Int -- | Does the element occur in the structure? -- -- Note: elem is often used in infix form. -- --
-- >>> 3 `elem` [] -- False ---- --
-- >>> 3 `elem` [1,2] -- False ---- --
-- >>> 3 `elem` [1,2,3,4,5] -- True ---- -- For infinite structures, the default implementation of elem -- terminates if the sought-after value exists at a finite distance from -- the left side of the structure: -- --
-- >>> 3 `elem` [1..] -- True ---- --
-- >>> 3 `elem` ([4..] ++ [3]) -- * Hangs forever * --elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The largest element of a non-empty structure. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. A structure that supports random access -- and maintains its elements in order should provide a specialised -- implementation to return the maximum in faster than linear time. -- --
-- >>> maximum [1..10] -- 10 ---- --
-- >>> maximum [] -- *** Exception: Prelude.maximum: empty list ---- --
-- >>> maximum Nothing -- *** Exception: maximum: empty structure ---- -- WARNING: This function is partial for possibly-empty structures like -- lists. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. A structure that supports random access -- and maintains its elements in order should provide a specialised -- implementation to return the minimum in faster than linear time. -- --
-- >>> minimum [1..10] -- 1 ---- --
-- >>> minimum [] -- *** Exception: Prelude.minimum: empty list ---- --
-- >>> minimum Nothing -- *** Exception: minimum: empty structure ---- -- WARNING: This function is partial for possibly-empty structures like -- lists. minimum :: (Foldable t, Ord a) => t a -> a infix 4 `elem` -- | Functors representing data structures that can be transformed to -- structures of the same shape by performing an -- Applicative (or, therefore, Monad) action on each -- element from left to right. -- -- A more detailed description of what same shape means, the -- various methods, how traversals are constructed, and example advanced -- use-cases can be found in the Overview section of -- Data.Traversable#overview. -- -- For the class laws see the Laws section of -- Data.Traversable#laws. class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. -- --
-- >>> traverse Just [1,2,3,4] -- Just [1,2,3,4] ---- --
-- >>> traverse id [Right 1, Right 2, Right 3, Right 4] -- Right [1,2,3,4] ---- -- In the next examples, we show that Nothing and Left -- values short circuit the created structure. -- --
-- >>> traverse (const Nothing) [1,2,3,4] -- Nothing ---- --
-- >>> traverse (\x -> if odd x then Just x else Nothing) [1,2,3,4] -- Nothing ---- --
-- >>> traverse id [Right 1, Right 2, Right 3, Right 4, Left 0] -- Left 0 --traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. -- --
-- >>> sequenceA [Just 1, Just 2, Just 3] -- Just [1,2,3] ---- --
-- >>> sequenceA [Right 1, Right 2, Right 3] -- Right [1,2,3] ---- -- The next two example show Nothing and Just will short -- circuit the resulting structure if present in the input. For more -- context, check the Traversable instances for Either and -- Maybe. -- --
-- >>> sequenceA [Just 1, Just 2, Just 3, Nothing] -- Nothing ---- --
-- >>> sequenceA [Right 1, Right 2, Right 3, Left 4] -- Left 4 --sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. -- --
-- >>> sequence $ Right [1,2,3,4] -- [Right 1,Right 2,Right 3,Right 4] ---- --
-- >>> sequence $ [Right 1,Right 2,Right 3,Right 4] -- Right [1,2,3,4] ---- -- The following examples demonstrate short circuit behavior for -- sequence. -- --
-- >>> sequence $ Left [1,2,3,4] -- Left [1,2,3,4] ---- --
-- >>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4] -- Left 0 --sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | The shows functions return a function that prepends the -- output String to an existing String. This allows -- constant-time concatenation of results using function composition. type ShowS = String -> String -- | A parser for a type a, represented as a function that takes a -- String and returns a list of possible parses as -- (a,String) pairs. -- -- Note that this kind of backtracking parser is very inefficient; -- reading a large structure may be quite slow (cf ReadP). type ReadS a = String -> [(a, String)] -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | General coercion to Fractional types. -- -- WARNING: This function goes through the Rational type, which -- does not have values for NaN for example. This means it does -- not round-trip. -- -- For Double it also behaves differently with or without -O0: -- --
-- Prelude> realToFrac nan -- With -O0 -- -Infinity -- Prelude> realToFrac nan -- NaN --realToFrac :: (Real a, Fractional b) => a -> b -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is representation-polymorphic in its -- result type, so that foo $ True where foo :: Bool -- -> Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
-- f x | x < 0 = ... -- | otherwise = ... --otherwise :: Bool -- | Append two lists, i.e., -- --
-- [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] -- [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...] ---- -- If the first list is not finite, the result is the first list. -- -- WARNING: This function takes linear time in the number of elements of -- the first list. (++) :: [a] -> [a] -> [a] infixr 5 ++ -- | <math>. map f xs is the list obtained by -- applying f to each element of xs, i.e., -- --
-- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- map f [x1, x2, ...] == [f x1, f x2, ...] ---- --
-- >>> map (+1) [1, 2, 3] -- [2,3,4] --map :: (a -> b) -> [a] -> [b] -- | error stops execution and displays an error message. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => [Char] -> a -- | <math>. zipWith generalises zip by zipping with -- the function given as the first argument, instead of a tupling -- function. -- --
-- zipWith (,) xs ys == zip xs ys -- zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..] ---- -- For example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums: -- --
-- >>> zipWith (+) [1, 2, 3] [4, 5, 6] -- [5,7,9] ---- -- zipWith is right-lazy: -- --
-- >>> let f = undefined -- -- >>> zipWith f [] undefined -- [] ---- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
-- ($) :: (a -> b) -> a -> b -- (<$>) :: Functor f => (a -> b) -> f a -> f b ---- -- Whereas $ is function application, <$> is function -- application lifted over a Functor. -- --
-- >>> show <$> Nothing -- Nothing -- -- >>> show <$> Just 3 -- Just "3" ---- -- Convert from an Either Int Int to an -- Either Int String using show: -- --
-- >>> show <$> Left 17 -- Left 17 -- -- >>> show <$> Right 17 -- Right "17" ---- -- Double each element of a list: -- --
-- >>> (*2) <$> [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> even <$> (2,2) -- (2,True) --(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | Extract the first component of a pair. fst :: (a, b) -> a -- | uncurry converts a curried function to a function on pairs. -- --
-- >>> uncurry (+) (1,2) -- 3 ---- --
-- >>> uncurry ($) (show, 1) -- "1" ---- --
-- >>> map (uncurry max) [(1,2), (3,4), (6,8)] -- [2,4,8] --uncurry :: (a -> b -> c) -> (a, b) -> c -- | <math>. Extract the first element of a list, which must be -- non-empty. -- --
-- >>> head [1, 2, 3] -- 1 -- -- >>> head [1..] -- 1 -- -- >>> head [] -- *** Exception: Prelude.head: empty list ---- -- WARNING: This function is partial. You can use case-matching, -- uncons or listToMaybe instead. head :: HasCallStack => [a] -> a -- | The computation writeFile file str function writes the -- string str, to the file file. writeFile :: FilePath -> String -> IO () -- | Read a line from the standard input device (same as hGetLine -- stdin). getLine :: IO String -- | The same as putStr, but adds a newline character. putStrLn :: String -> IO () -- | <math>. filter, applied to a predicate and a list, -- returns the list of those elements that satisfy the predicate; i.e., -- --
-- filter p xs = [ x | x <- xs, p x] ---- --
-- >>> filter odd [1, 2, 3] -- [1,3] --filter :: (a -> Bool) -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. -- --
-- >>> cycle [] -- *** Exception: Prelude.cycle: empty list -- -- >>> cycle [42] -- [42,42,42,42,42,42,42,42,42,42... -- -- >>> cycle [2, 5, 7] -- [2,5,7,2,5,7,2,5,7,2,5,7... --cycle :: HasCallStack => [a] -> [a] -- | The value of seq a b is bottom if a is -- bottom, and otherwise equal to b. In other words, it -- evaluates the first argument a to weak head normal form -- (WHNF). seq is usually introduced to improve performance by -- avoiding unneeded laziness. -- -- A note on evaluation order: the expression seq a b -- does not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq returns -- a value. In particular, this means that b may be evaluated -- before a. If you need to guarantee a specific order of -- evaluation, you must use the function pseq from the -- "parallel" package. seq :: forall {r :: RuntimeRep} a (b :: TYPE r). a -> b -> b infixr 0 `seq` -- | The concatenation of all the elements of a container of lists. -- --
-- >>> concat (Just [1, 2, 3]) -- [1,2,3] ---- --
-- >>> concat (Left 42) -- [] ---- --
-- >>> concat [[1, 2, 3], [4, 5], [6], []] -- [1,2,3,4,5,6] --concat :: Foldable t => t [a] -> [a] -- | <math>. zip takes two lists and returns a list of -- corresponding pairs. -- --
-- >>> zip [1, 2] ['a', 'b'] -- [(1,'a'),(2,'b')] ---- -- If one input list is shorter than the other, excess elements of the -- longer list are discarded, even if one of the lists is infinite: -- --
-- >>> zip [1] ['a', 'b'] -- [(1,'a')] -- -- >>> zip [1, 2] ['a'] -- [(1,'a')] -- -- >>> zip [] [1..] -- [] -- -- >>> zip [1..] [] -- [] ---- -- zip is right-lazy: -- --
-- >>> zip [] undefined -- [] -- -- >>> zip undefined [] -- *** Exception: Prelude.undefined -- ... ---- -- zip is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | The print function outputs a value of any printable type to the -- standard output device. Printable types are those that are instances -- of class Show; print converts values to strings for -- output using the show operation and adds a newline. -- -- For example, a program to print the first 20 integers and their powers -- of 2 could be written as: -- --
-- main = print ([(n, 2^n) | n <- [0..19]]) --print :: Show a => a -> IO () -- | Boolean "and", lazy in the second argument (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or", lazy in the second argument (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | A variant of error that does not produce a stack trace. errorWithoutStackTrace :: forall (r :: RuntimeRep) (a :: TYPE r). [Char] -> a -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | const x y always evaluates to x, ignoring its second -- argument. -- --
-- >>> const 42 "hello" -- 42 ---- --
-- >>> map (const 42) [0..3] -- [42,42,42,42] --const :: a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
-- >>> flip (++) "hello" "world" -- "worldhello" --flip :: (a -> b -> c) -> b -> a -> c -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $! -- | until p f yields the result of applying f -- until p holds. until :: (a -> Bool) -> (a -> a) -> a -> a -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --
-- >>> maybe False odd (Just 3) -- True ---- --
-- >>> maybe False odd Nothing -- False ---- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> maybe 0 (*2) (readMaybe "5") -- 10 -- -- >>> maybe 0 (*2) (readMaybe "") -- 0 ---- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
-- >>> maybe "" show (Just 5) -- "5" -- -- >>> maybe "" show Nothing -- "" --maybe :: b -> (a -> b) -> Maybe a -> b -- | <math>. Extract the elements after the head of a list, which -- must be non-empty. -- --
-- >>> tail [1, 2, 3] -- [2,3] -- -- >>> tail [1] -- [] -- -- >>> tail [] -- *** Exception: Prelude.tail: empty list ---- -- WARNING: This function is partial. You can use case-matching or -- uncons instead. tail :: HasCallStack => [a] -> [a] -- | <math>. Extract the last element of a list, which must be finite -- and non-empty. -- --
-- >>> last [1, 2, 3] -- 3 -- -- >>> last [1..] -- * Hangs forever * -- -- >>> last [] -- *** Exception: Prelude.last: empty list ---- -- WARNING: This function is partial. You can use reverse with -- case-matching, uncons or listToMaybe instead. last :: HasCallStack => [a] -> a -- | <math>. Return all the elements of a list except the last one. -- The list must be non-empty. -- --
-- >>> init [1, 2, 3] -- [1,2] -- -- >>> init [1] -- [] -- -- >>> init [] -- *** Exception: Prelude.init: empty list ---- -- WARNING: This function is partial. You can use reverse with -- case-matching or uncons instead. init :: HasCallStack => [a] -> [a] -- | <math>. scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs ---- --
-- >>> scanl (+) 0 [1..4] -- [0,1,3,6,10] -- -- >>> scanl (+) 42 [] -- [42] -- -- >>> scanl (-) 100 [1..4] -- [100,99,97,94,90] -- -- >>> scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd'] -- ["foo","afoo","bafoo","cbafoo","dcbafoo"] -- -- >>> scanl (+) 0 [1..] -- * Hangs forever * --scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | <math>. scanl1 is a variant of scanl that has no -- starting value argument: -- --
-- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] ---- --
-- >>> scanl1 (+) [1..4] -- [1,3,6,10] -- -- >>> scanl1 (+) [] -- [] -- -- >>> scanl1 (-) [1..4] -- [1,-1,-4,-8] -- -- >>> scanl1 (&&) [True, False, True, True] -- [True,False,False,False] -- -- >>> scanl1 (||) [False, False, True, True] -- [False,False,True,True] -- -- >>> scanl1 (+) [1..] -- * Hangs forever * --scanl1 :: (a -> a -> a) -> [a] -> [a] -- | <math>. scanr is the right-to-left dual of scanl. -- Note that the order of parameters on the accumulating function are -- reversed compared to scanl. Also note that -- --
-- head (scanr f z xs) == foldr f z xs. ---- --
-- >>> scanr (+) 0 [1..4] -- [10,9,7,4,0] -- -- >>> scanr (+) 42 [] -- [42] -- -- >>> scanr (-) 100 [1..4] -- [98,-97,99,-96,100] -- -- >>> scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd'] -- ["abcdfoo","bcdfoo","cdfoo","dfoo","foo"] -- -- >>> force $ scanr (+) 0 [1..] -- *** Exception: stack overflow --scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | <math>. scanr1 is a variant of scanr that has no -- starting value argument. -- --
-- >>> scanr1 (+) [1..4] -- [10,9,7,4] -- -- >>> scanr1 (+) [] -- [] -- -- >>> scanr1 (-) [1..4] -- [-2,3,-1,4] -- -- >>> scanr1 (&&) [True, False, True, True] -- [False,False,True,True] -- -- >>> scanr1 (||) [True, True, False, False] -- [True,True,False,False] -- -- >>> force $ scanr1 (+) [1..] -- *** Exception: stack overflow --scanr1 :: (a -> a -> a) -> [a] -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
-- iterate f x == [x, f x, f (f x), ...] ---- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. -- --
-- >>> take 10 $ iterate not True -- [True,False,True,False... -- -- >>> take 10 $ iterate (+3) 42 -- [42,45,48,51,54,57,60,63... --iterate :: (a -> a) -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. -- --
-- >>> repeat 17 -- [17,17,17,17,17,17,17,17,17... --repeat :: a -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. -- --
-- >>> replicate 0 True -- [] -- -- >>> replicate (-1) True -- [] -- -- >>> replicate 4 True -- [True,True,True,True] --replicate :: Int -> a -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p. -- --
-- >>> takeWhile (< 3) [1,2,3,4,1,2,3,4] -- [1,2] -- -- >>> takeWhile (< 9) [1,2,3] -- [1,2,3] -- -- >>> takeWhile (< 0) [1,2,3] -- [] --takeWhile :: (a -> Bool) -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. -- --
-- >>> dropWhile (< 3) [1,2,3,4,5,1,2,3] -- [3,4,5,1,2,3] -- -- >>> dropWhile (< 9) [1,2,3] -- [] -- -- >>> dropWhile (< 0) [1,2,3] -- [1,2,3] --dropWhile :: (a -> Bool) -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n >= length xs. -- --
-- >>> take 5 "Hello World!" -- "Hello" -- -- >>> take 3 [1,2,3,4,5] -- [1,2,3] -- -- >>> take 3 [1,2] -- [1,2] -- -- >>> take 3 [] -- [] -- -- >>> take (-1) [1,2] -- [] -- -- >>> take 0 [1,2] -- [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n >= length -- xs. -- --
-- >>> drop 6 "Hello World!" -- "World!" -- -- >>> drop 3 [1,2,3,4,5] -- [4,5] -- -- >>> drop 3 [1,2] -- [] -- -- >>> drop 3 [] -- [] -- -- >>> drop (-1) [1,2] -- [1,2] -- -- >>> drop 0 [1,2] -- [1,2] ---- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
-- >>> splitAt 6 "Hello World!"
-- ("Hello ","World!")
--
-- >>> splitAt 3 [1,2,3,4,5]
-- ([1,2,3],[4,5])
--
-- >>> splitAt 1 [1,2,3]
-- ([1],[2,3])
--
-- >>> splitAt 3 [1,2,3]
-- ([1,2,3],[])
--
-- >>> splitAt 4 [1,2,3]
-- ([1,2,3],[])
--
-- >>> splitAt 0 [1,2,3]
-- ([],[1,2,3])
--
-- >>> splitAt (-1) [1,2,3]
-- ([],[1,2,3])
--
--
-- It is equivalent to (take n xs, drop n xs) when
-- n is not _|_ (splitAt _|_ xs = _|_).
-- splitAt is an instance of the more general
-- genericSplitAt, in which n may be of any integral
-- type.
splitAt :: Int -> [a] -> ([a], [a])
-- | span, applied to a predicate p and a list xs,
-- returns a tuple where first element is longest prefix (possibly empty)
-- of xs of elements that satisfy p and second element
-- is the remainder of the list:
--
-- -- >>> span (< 3) [1,2,3,4,1,2,3,4] -- ([1,2],[3,4,1,2,3,4]) -- -- >>> span (< 9) [1,2,3] -- ([1,2,3],[]) -- -- >>> span (< 0) [1,2,3] -- ([],[1,2,3]) ---- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: (a -> Bool) -> [a] -> ([a], [a]) -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
-- >>> break (> 3) [1,2,3,4,1,2,3,4] -- ([1,2,3],[4,1,2,3,4]) -- -- >>> break (< 9) [1,2,3] -- ([],[1,2,3]) -- -- >>> break (> 9) [1,2,3] -- ([1,2,3],[]) ---- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. -- --
-- >>> reverse [] -- [] -- -- >>> reverse [42] -- [42] -- -- >>> reverse [2,5,7] -- [7,5,2] -- -- >>> reverse [1..] -- * Hangs forever * --reverse :: [a] -> [a] -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. -- --
-- >>> and [] -- True ---- --
-- >>> and [True] -- True ---- --
-- >>> and [False] -- False ---- --
-- >>> and [True, True, False] -- False ---- --
-- >>> and (False : repeat True) -- Infinite list [False,True,True,True,... -- False ---- --
-- >>> and (repeat True) -- * Hangs forever * --and :: Foldable t => t Bool -> Bool -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. -- --
-- >>> or [] -- False ---- --
-- >>> or [True] -- True ---- --
-- >>> or [False] -- False ---- --
-- >>> or [True, True, False] -- True ---- --
-- >>> or (True : repeat False) -- Infinite list [True,False,False,False,... -- True ---- --
-- >>> or (repeat False) -- * Hangs forever * --or :: Foldable t => t Bool -> Bool -- | Determines whether any element of the structure satisfies the -- predicate. -- --
-- >>> any (> 3) [] -- False ---- --
-- >>> any (> 3) [1,2] -- False ---- --
-- >>> any (> 3) [1,2,3,4,5] -- True ---- --
-- >>> any (> 3) [1..] -- True ---- --
-- >>> any (> 3) [0, -1..] -- * Hangs forever * --any :: Foldable t => (a -> Bool) -> t a -> Bool -- | Determines whether all elements of the structure satisfy the -- predicate. -- --
-- >>> all (> 3) [] -- True ---- --
-- >>> all (> 3) [1,2] -- False ---- --
-- >>> all (> 3) [1,2,3,4,5] -- False ---- --
-- >>> all (> 3) [1..] -- False ---- --
-- >>> all (> 3) [4..] -- * Hangs forever * --all :: Foldable t => (a -> Bool) -> t a -> Bool -- | notElem is the negation of elem. -- --
-- >>> 3 `notElem` [] -- True ---- --
-- >>> 3 `notElem` [1,2] -- True ---- --
-- >>> 3 `notElem` [1,2,3,4,5] -- False ---- -- For infinite structures, notElem terminates if the value exists -- at a finite distance from the left side of the structure: -- --
-- >>> 3 `notElem` [1..] -- False ---- --
-- >>> 3 `notElem` ([4..] ++ [3]) -- * Hangs forever * --notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | <math>. lookup key assocs looks up a key in an -- association list. For the result to be Nothing, the list must -- be finite. -- --
-- >>> lookup 2 [] -- Nothing -- -- >>> lookup 2 [(1, "first")] -- Nothing -- -- >>> lookup 2 [(1, "first"), (2, "second"), (3, "third")] -- Just "second" --lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | Map a function over all the elements of a container and concatenate -- the resulting lists. -- --
-- >>> concatMap (take 3) [[1..], [10..], [100..], [1000..]] -- [1,2,3,10,11,12,100,101,102,1000,1001,1002] ---- --
-- >>> concatMap (take 3) (Just [1..]) -- [1,2,3] --concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | List index (subscript) operator, starting from 0. It is an instance of -- the more general genericIndex, which takes an index of any -- integral type. -- --
-- >>> ['a', 'b', 'c'] !! 0 -- 'a' -- -- >>> ['a', 'b', 'c'] !! 2 -- 'c' -- -- >>> ['a', 'b', 'c'] !! 3 -- *** Exception: Prelude.!!: index too large -- -- >>> ['a', 'b', 'c'] !! (-1) -- *** Exception: Prelude.!!: negative index ---- -- WARNING: This function is partial. You can use atMay instead. (!!) :: HasCallStack => [a] -> Int -> a infixl 9 !! -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of the function -- applied to corresponding elements, analogous to zipWith. It is -- capable of list fusion, but it is restricted to its first list -- argument and its resulting list. -- --
-- zipWith3 (,,) xs ys zs == zip3 xs ys zs -- zipWith3 f [x1,x2,x3..] [y1,y2,y3..] [z1,z2,z3..] == [f x1 y1 z1, f x2 y2 z2, f x3 y3 z3..] --zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. -- --
-- >>> unzip [] -- ([],[]) -- -- >>> unzip [(1, 'a'), (2, 'b')] -- ([1,2],"ab") --unzip :: [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. -- --
-- >>> unzip3 [] -- ([],[],[]) -- -- >>> unzip3 [(1, 'a', True), (2, 'b', False)] -- ([1,2],"ab",[True,False]) --unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | equivalent to showsPrec with a precedence of 0. shows :: Show a => a -> ShowS -- | utility function converting a Char to a show function that -- simply prepends the character unchanged. showChar :: Char -> ShowS -- | utility function converting a String to a show function that -- simply prepends the string unchanged. showString :: String -> ShowS -- | utility function that surrounds the inner show function with -- parentheses when the Bool parameter is True. showParen :: Bool -> ShowS -> ShowS -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | Extract the second component of a pair. snd :: (a, b) -> b -- | curry converts an uncurried function to a curried function. -- --
-- >>> curry fst 1 2 -- 1 --curry :: ((a, b) -> c) -> a -> b -> c -- | The lex function reads a single lexeme from the input, -- discarding initial white space, and returning the characters that -- constitute the lexeme. If the input string contains only white space, -- lex returns a single successful `lexeme' consisting of the -- empty string. (Thus lex "" = [("","")].) If there is -- no legal lexeme at the beginning of the input string, lex fails -- (i.e. returns []). -- -- This lexer is not completely faithful to the Haskell lexical syntax in -- the following respects: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> either length (*2) s -- 3 -- -- >>> either length (*2) n -- 6 --either :: (a -> c) -> (b -> c) -> Either a b -> c -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | The read function reads input from a string, which must be -- completely consumed by the input process. read fails with an -- error if the parse is unsuccessful, and it is therefore -- discouraged from being used in real applications. Use readMaybe -- or readEither for safe alternatives. -- --
-- >>> read "123" :: Int -- 123 ---- --
-- >>> read "hello" :: Int -- *** Exception: Prelude.read: no parse --read :: Read a => String -> a -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and ignore the results. For a version that -- doesn't ignore the results see mapM. -- -- mapM_ is just like traverse_, but specialised to monadic -- actions. mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () -- | Evaluate each monadic action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results see -- sequence. -- -- sequence_ is just like sequenceA_, but specialised to -- monadic actions. sequence_ :: (Foldable t, Monad m) => t (m a) -> m () -- | Splits the argument into a list of lines stripped of their -- terminating \n characters. The \n terminator is -- optional in a final non-empty line of the argument string. -- -- For example: -- --
-- >>> lines "" -- empty input contains no lines -- [] -- -- >>> lines "\n" -- single empty line -- [""] -- -- >>> lines "one" -- single unterminated line -- ["one"] -- -- >>> lines "one\n" -- single non-empty line -- ["one"] -- -- >>> lines "one\n\n" -- second line is empty -- ["one",""] -- -- >>> lines "one\ntwo" -- second line is unterminated -- ["one","two"] -- -- >>> lines "one\ntwo\n" -- two non-empty lines -- ["one","two"] ---- -- When the argument string is empty, or ends in a \n character, -- it can be recovered by passing the result of lines to the -- unlines function. Otherwise, unlines appends the missing -- terminating \n. This makes unlines . lines -- idempotent: -- --
-- (unlines . lines) . (unlines . lines) = (unlines . lines) --lines :: String -> [String] -- | Appends a \n character to each input string, then -- concatenates the results. Equivalent to foldMap (s -> -- s ++ "\n"). -- --
-- >>> unlines ["Hello", "World", "!"] -- "Hello\nWorld\n!\n" ---- -- Note that unlines . lines /= -- id when the input is not \n-terminated: -- --
-- >>> unlines . lines $ "foo\nbar" -- "foo\nbar\n" --unlines :: [String] -> String -- | words breaks a string up into a list of words, which were -- delimited by white space (as defined by isSpace). This function -- trims any white spaces at the beginning and at the end. -- --
-- >>> words "Lorem ipsum\ndolor" -- ["Lorem","ipsum","dolor"] -- -- >>> words " foo bar " -- ["foo","bar"] --words :: String -> [String] -- | unwords joins words with separating spaces (U+0020 SPACE). -- --
-- >>> unwords ["Lorem", "ipsum", "dolor"] -- "Lorem ipsum dolor" ---- -- unwords is neither left nor right inverse of words: -- --
-- >>> words (unwords [" "]) -- [] -- -- >>> unwords (words "foo\nbar") -- "foo bar" --unwords :: [String] -> String -- | Construct an IOException value with a string describing the -- error. The fail method of the IO instance of the -- Monad class raises a userError, thus: -- --
-- instance Monad IO where -- ... -- fail s = ioError (userError s) --userError :: String -> IOError -- | Raise an IOException in the IO monad. ioError :: IOError -> IO a -- | Write a character to the standard output device (same as -- hPutChar stdout). putChar :: Char -> IO () -- | Write a string to the standard output device (same as hPutStr -- stdout). putStr :: String -> IO () -- | Read a character from the standard input device (same as -- hGetChar stdin). getChar :: IO Char -- | The getContents operation returns all user input as a single -- string, which is read lazily as it is needed (same as -- hGetContents stdin). getContents :: IO String -- | The interact function takes a function of type -- String->String as its argument. The entire input from the -- standard input device is passed to this function as its argument, and -- the resulting string is output on the standard output device. interact :: (String -> String) -> IO () -- | The readFile function reads a file and returns the contents of -- the file as a string. The file is read lazily, on demand, as with -- getContents. readFile :: FilePath -> IO String -- | The computation appendFile file str function appends -- the string str, to the file file. -- -- Note that writeFile and appendFile write a literal -- string to a file. To write a value of any printable type, as with -- print, use the show function to convert the value to a -- string first. -- --
-- main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) --appendFile :: FilePath -> String -> IO () -- | The readLn function combines getLine and readIO. readLn :: Read a => IO a -- | The readIO function is similar to read except that it -- signals parse failure to the IO monad instead of terminating -- the program. readIO :: Read a => String -> IO a