-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoperation-product.R
81 lines (62 loc) · 2.21 KB
/
operation-product.R
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
new_operation_product = function(list) {
new("operation_product", .Data = list)
}
#' @rdname operation_product
#' @export
setMethod("prod", signature(x = "operation"), function(x, ..., na.rm = FALSE) {
new_operation_product(list(x, ...))
})
# type conversion ---------------------------------------------------------
setAs("list", "operation_product", function(from) {
new_operation_product(lapply(from, as, "operation"))
})
setAs("operation", "operation_product", function(from) new_operation_product(list(from)))
# operation application ---------------------------------------------------
setMethod("apply_operation", signature(operation = "operation_product"), function(operation, layers) {
Reduce(`*`, [email protected], layers)
})
# operation multiplication -------------------------------------------------
#' @rdname operation_product
#' @export
setMethod("*", signature(e1 = "operation", e2 = "operation"), function(e1, e2) {
e1 = as(e1, "operation_product")
e2 = as(e2, "operation_product")
new_operation_product(c(e1, e2))
})
#' @rdname operation_product
#' @export
setMethod("*", signature(e1 = "numeric", e2 = "operation"), function(e1, e2) {
e2 = as(e2, "operation_product")
operations = rep([email protected], times = e1)
new_operation_sum(operations)
})
#' @rdname operation_product
#' @export
setMethod("*", signature(e1 = "operation", e2 = "numeric"), function(e1, e2) {
e2 * e1
})
#' @rdname operation_product
#' @export
setMethod("*", signature(e1 = "operation", e2 = "operation_sum"), function(e1, e2) {
new_operation_sum(lapply(e2, `*`, e1 = e1))
})
#' @rdname operation_product
#' @export
setMethod("*", signature(e1 = "operation_sum", e2 = "operation"), function(e1, e2) {
new_operation_sum(lapply(e1, `*`, e2 = e2))
})
#' @rdname operation_product
#' @export
setMethod("*", signature(e1 = "operation_sum", e2 = "operation_sum"), function(e1, e2) {
new_operation_sum(do.call(c, lapply(e1, `*`, e2 = e2)))
})
# printing ----------------------------------------------------------------
#' @rdname operation-class
#' @export
setMethod("format", signature(x = "operation_product"), function(x, ...) {
if (length(x) == 0) {
"0"
} else {
paste(vapply(x, format, character(1)), collapse = " * ")
}
})