module NumericPrelude.Elementwise where

import Control.Applicative (Applicative(pure, (<*>)), )

{- |
A reader monad for the special purpose
of defining instances of certain operations on tuples and records.
It does not add any new functionality to the common Reader monad,
but it restricts the functions to the required ones
and exports them from one module.
That is you do not have to import
both Control.Monad.Trans.Reader and Control.Applicative.
The type also tells the user, for what the Reader monad is used.
We can more easily replace or extend the implementation when needed.
-}
newtype T v a = Cons {T v a -> v -> a
run :: v -> a}

{-# INLINE with #-}
with :: a -> T v a
with :: a -> T v a
with a
e = (v -> a) -> T v a
forall v a. (v -> a) -> T v a
Cons ((v -> a) -> T v a) -> (v -> a) -> T v a
forall a b. (a -> b) -> a -> b
$ \ v
_v -> a
e

{-# INLINE element #-}
element :: (v -> a) -> T v a
element :: (v -> a) -> T v a
element = (v -> a) -> T v a
forall v a. (v -> a) -> T v a
Cons


{-# INLINE run2 #-}
run2 :: T (x,y) a -> x -> y -> a
run2 :: T (x, y) a -> x -> y -> a
run2 = ((x, y) -> a) -> x -> y -> a
forall a b c. ((a, b) -> c) -> a -> b -> c
curry (((x, y) -> a) -> x -> y -> a)
-> (T (x, y) a -> (x, y) -> a) -> T (x, y) a -> x -> y -> a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. T (x, y) a -> (x, y) -> a
forall v a. T v a -> v -> a
run

{-# INLINE run3 #-}
run3 :: T (x,y,z) a -> x -> y -> z -> a
run3 :: T (x, y, z) a -> x -> y -> z -> a
run3 T (x, y, z) a
e x
x y
y z
z = T (x, y, z) a -> (x, y, z) -> a
forall v a. T v a -> v -> a
run T (x, y, z) a
e (x
x,y
y,z
z)

{-# INLINE run4 #-}
run4 :: T (x,y,z,w) a -> x -> y -> z -> w -> a
run4 :: T (x, y, z, w) a -> x -> y -> z -> w -> a
run4 T (x, y, z, w) a
e x
x y
y z
z w
w = T (x, y, z, w) a -> (x, y, z, w) -> a
forall v a. T v a -> v -> a
run T (x, y, z, w) a
e (x
x,y
y,z
z,w
w)

{-# INLINE run5 #-}
run5 :: T (x,y,z,u,w) a -> x -> y -> z -> u -> w -> a
run5 :: T (x, y, z, u, w) a -> x -> y -> z -> u -> w -> a
run5 T (x, y, z, u, w) a
e x
x y
y z
z u
u w
w = T (x, y, z, u, w) a -> (x, y, z, u, w) -> a
forall v a. T v a -> v -> a
run T (x, y, z, u, w) a
e (x
x,y
y,z
z,u
u,w
w)


instance Functor (T v) where
   {-# INLINE fmap #-}
   fmap :: (a -> b) -> T v a -> T v b
fmap a -> b
f (Cons v -> a
e) =
      (v -> b) -> T v b
forall v a. (v -> a) -> T v a
Cons ((v -> b) -> T v b) -> (v -> b) -> T v b
forall a b. (a -> b) -> a -> b
$ \v
v -> a -> b
f (a -> b) -> a -> b
forall a b. (a -> b) -> a -> b
$ v -> a
e v
v

instance Applicative (T v) where
   {-# INLINE pure #-}
   {-# INLINE (<*>) #-}
   pure :: a -> T v a
pure = a -> T v a
forall a v. a -> T v a
with
   Cons v -> a -> b
f <*> :: T v (a -> b) -> T v a -> T v b
<*> Cons v -> a
e =
      (v -> b) -> T v b
forall v a. (v -> a) -> T v a
Cons ((v -> b) -> T v b) -> (v -> b) -> T v b
forall a b. (a -> b) -> a -> b
$ \v
v -> v -> a -> b
f v
v (a -> b) -> a -> b
forall a b. (a -> b) -> a -> b
$ v -> a
e v
v