@@ -1,8 +1,66 @@
11module LinearAlgebra.Vector
22 ( Vector
3+ , add
4+ , argmax
5+ , argmin
6+ , diff
7+ , dot
8+ , sum
39 ) where
410
11+import Prelude
12+import Global (infinity)
13+import Data.Array as A
14+import Data.Maybe (Maybe(..))
15+import Data.Tuple (Tuple(..), fst, snd)
16+
517
618-- | Dense Vector implementation
719type Vector = Array
8−
20+
21+
22+-- | Difference between 2 vectors.
23+-- | Vector have to have the same size
24+diff :: Vector Number -> Vector Number -> Maybe (Vector Number)
25+diff xs ys
26+ | (A.length xs) /= (A.length ys) = Nothing
27+ | otherwise = Just $ A.zipWith (-) xs ys
28+
29+
30+-- | Add 2 vectors.
31+-- | Vector have to have the same size
32+add :: ∀ a. Semiring a => Vector a -> Vector a -> Maybe (Vector a)
33+add xs ys
34+ | (A.length xs) /= (A.length ys) = Nothing
35+ | otherwise = Just $ A.zipWith (+) xs ys
36+
37+
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
41+dot xs ys
42+ | (A.length xs) /= (A.length ys) = Nothing
43+ | otherwise = Just $ sum (A.zipWith (*) xs ys)
44+
45+
46+-- | Sum vector elements
47+sum :: ∀ a. Semiring a => Vector a -> a
48+sum xs = A.foldl (+) zero xs
49+
50+
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
55+ where
56+ xs = A.mapWithIndex Tuple vs
57+ f tu tv = if (snd tv) > (snd tu) then tv else tu
58+
59+
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
64+ where
65+ xs = A.mapWithIndex Tuple vs
66+ f tu tv = if (snd tv) < (snd tu) then tv else tu