{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module ProductMixAuction.LinearAlgebra where
import Prelude
import Data.Vector (Vector)
import qualified Data.Vector as V
import GHC.Exts (IsList (..))
type Dimension = Int
class ComponentWise f where
componentWise :: (a -> b -> c) -> f a -> f b -> f c
instance ComponentWise [] where
componentWise = zipWith
instance ComponentWise Vector where
componentWise = V.zipWith
isZero :: (Foldable f, Eq a, Num a) => f a -> Bool
isZero v = length v == 0 || all (== 0) v
zero :: (Num (Item (f a)), IsList (f a)) => Dimension -> f a
zero dim = fromList $ replicate dim 0
ones :: (Num (Item (f a)), IsList (f a)) => Dimension -> f a
ones dim = fromList $ replicate dim 1
vplus :: (Num a, ComponentWise f) => f a -> f a -> f a
vplus = componentWise (+)
(<+>) :: (Num a, ComponentWise f) => f a -> f a -> f a
(<+>) = vplus
vminus :: (Num a, ComponentWise f) => f a -> f a -> f a
vminus = componentWise (-)
(<->) :: (Num a, ComponentWise f) => f a -> f a -> f a
(<->) = vminus
(<.>) :: (Num a, ComponentWise f) => f a -> f a -> f a
(<.>) = componentWise (*)
vmax :: (Ord a, ComponentWise f) => f a -> f a -> f a
vmax = componentWise max
vmin :: (Ord a, ComponentWise f) => f a -> f a -> f a
vmin = componentWise min
vscale :: (Functor f, Num a) => a -> f a -> f a
vscale s = fmap (* s)
vlte :: (Ord a, Functor f, ComponentWise f, Foldable f) => f a -> f a -> Bool
vlte x y = and $ componentWise (<=) x y
dot :: (Num a, Functor f, ComponentWise f, Foldable f)
=> f a -> f a -> a
dot = dotBy (*)
dotBy :: (Num c, Functor f, ComponentWise f, Foldable f)
=> (a -> b -> c)
-> f a
-> f b
-> c
dotBy op x y = sum (componentWise op x y)
dot1 :: (Num a) => Vector a -> a
dot1 = V.sum