-
Notifications
You must be signed in to change notification settings - Fork 9
/
vector.ast
63 lines (55 loc) · 1.94 KB
/
vector.ast
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
------------------------------------------------------------------
-- vector.ast
--
-- this module defines functions useful for vector arithmetic
--
-- (c) University of Rhode Island
------------------------------------------------------------------
load system util.
------------------------------------------------------------------
function add
------------------------------------------------------------------
with (a,b) do
return op(lambda with (x,y) do x+y,a,b).
end
------------------------------------------------------------------
function dot
-- computes the dot product of two lists
------------------------------------------------------------------
with (a:%list,b:%list) do
return mult(a,b) @reduce(lambda with (x,y) do x+y).
end
------------------------------------------------------------------
function mult
------------------------------------------------------------------
with (a,b) do
return op(lambda with (x,y) do x*y,a,b).
end
------------------------------------------------------------------
function op
------------------------------------------------------------------
-- worker function for actual vector arithmetic
-- Note: it also implements vector/scalar arithmetic
with (f:%function,a:%list,b:%list) do
if a @length() =/= b @length() do
throw Error("vector operations only defined on lists of the same length").
end
let v = util @zip(a,b).
return v @map(f).
with (f:%function,a:%list,b if isscalar b) do
-- promote b to a vector
let bv = [1 to a @length()] @map(lambda with _ do b).
let v = util @zip(a,bv).
return v @map(f).
with (f:%function,a if isscalar a,b:%list) do
-- promote a to a vector
let av = [1 to b @length()] @map(lambda with _ do a).
let v = util @zip(av,b).
return v @map(f).
end
------------------------------------------------------------------
function sub
------------------------------------------------------------------
with (a,b) do
return op(lambda with (x,y) do x-y,a,b).
end