@@ -1,8 +1,66 @@
1module LinearAlgebra.Vector
1module LinearAlgebra.Vector
12+import Global (infinity)
13+import Data.Array as A
14+import Data.Maybe (Maybe(..))
15+import Data.Tuple (Tuple(..), fst, snd)
6-- | Dense Vector implementation
18-- | Dense Vector implementation
7type Vector = Array
19type Vector = Array
22+-- | Difference between 2 vectors.
23+-- | Vector have to have the same size
24+diff :: Vector Number -> Vector Number -> Maybe (Vector Number)
26+ | (A.length xs) /= (A.length ys) = Nothing
27+ | otherwise = Just $ A.zipWith (-) xs ys
31+-- | Vector have to have the same size
32+add :: ∀ a. Semiring a => Vector a -> Vector a -> Maybe (Vector a)
34+ | (A.length xs) /= (A.length ys) = Nothing
35+ | otherwise = Just $ A.zipWith (+) xs ys
38+-- | Dot product between 2 vectors
39+-- | https://en.wikipedia.org/wiki/Dot_product
40+dot :: ∀ a. Semiring a => Vector a -> Vector a -> Maybe a
42+ | (A.length xs) /= (A.length ys) = Nothing
43+ | otherwise = Just $ sum (A.zipWith (*) xs ys)
46+-- | Sum vector elements
47+sum :: ∀ a. Semiring a => Vector a -> a
48+sum xs = A.foldl (+) zero xs
51+-- | Return index of the first maximum value
52+-- | This function will return 0 index for empty vector
53+argmax :: Vector Number -> Int
54+argmax vs = fst $ A.foldl f (Tuple 0 (-infinity)) xs
56+ xs = A.mapWithIndex Tuple vs
57+ f tu tv = if (snd tv) > (snd tu) then tv else tu
60+-- | Return index of the first minimum value
61+-- | This function will return 0 index for empty vector
62+argmin :: Vector Number -> Int
63+argmin vs = fst $ A.foldl f (Tuple 0 infinity) xs
65+ xs = A.mapWithIndex Tuple vs
66+ f tu tv = if (snd tv) < (snd tu) then tv else tu