-
Notifications
You must be signed in to change notification settings - Fork 4
/
examples.hs
87 lines (70 loc) · 2.09 KB
/
examples.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
{-# LANGUAGE NoImplicitPrelude #-}
import Protolude
import Data.Vector as V
import Numeric.LinearAlgebra as H
-- |
-- >>> let x = V.fromList [0..5]
-- >>> V.length x
-- 6
--
-- >>> V.null x
-- False
-- | hmatrix examples
-- >>> let x = (2><2) [0..3] :: Matrix Double
-- >>> x
-- (2><2)
-- [ 0.0, 1.0
-- , 2.0, 3.0 ]
--
-- Matrix multiplication
-- >>> let y = fromLists [[0, 1], [2, 3]] :: Matrix Double
-- >>> x H.<> y
-- (2><2)
-- [ 2.0, 3.0
-- , 6.0, 11.0 ]
main :: IO ()
main = do
-- vector examples
let x = V.fromList [0..5]
print $ V.length x -- 6
print $ V.null x -- False
-- indexing
print $ x V.! 1 -- 1
print $ V.head x -- 0
print $ last x -- 5
-- Slicing
print $ slice 2 3 x -- [2, 3, 4]
print $ V.splitAt 2 x -- ([0, 1], [2, 3, 4, 5])
-- Prepending and Appending
print $ cons (-1) x -- [-1, 0, 1, 2, 3, 4, 5]
print $ snoc x 6 -- [0, 1, 2, 3, 4, 5, 6]
-- Concatenation
print $ x V.++ x -- [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]
print $ V.concat [x, x] -- [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]
-- Update
print $ x // [(0, 1), (2, 6)] -- [1, 1, 6, 3, 4, 5]
print $ V.map (+2) x -- [2, 3, 4, 5, 6, 7]
-- hmatrix examples
-- Creating matrices
let x = (2><2) [0..3] :: Matrix Double
-- [ 0.0, 1.0
-- , 2.0, 3.0 ]
let y = fromLists [[0, 1], [2, 3]] :: Matrix Double
-- Random matrices
r <- randn 2 3
-- [ 0.7764496757867578, 1.246311658930589, -0.684233085372455
-- , -2.540045307941425, -0.20975584071908912, -9.039537343065803e-3 ]
-- Matrix multiplication
print $ x H.<> y -- [ 2.0, 3.0
-- , 6.0, 11.0 ]
-- Transpose
print $ tr x -- [ 0.0, 2.0
-- , 1.0, 3.0 ]
-- Matrix slicing
print $ r ?? (H.All, Take 2) -- [ 0.7764496757867578, 1.246311658930589
-- , -2.540045307941425, -0.20975584071908912 ]
-- Mapping over matrices
print $ cmap ((+ 2) . (*2)) x -- [ 2.0, 4.0
-- , 6.0, 8.0 ]
-- Flatten
print $ flatten x -- [0.0, 1.0, 2.0, 3.0]