Skip to content

Instantly share code, notes, and snippets.

@bquast
Created Nov 11, 2019
Embed
What would you like to do?
# contructor function
tensor <- function(x) {
# check that it's numeric
if (!is.numeric(x)) stop("X must be numeric")
# create the array and change the class
y <- structure(array(x), class = "tensor")
# add attributes
attributes(y)$creators <- list()
attributes(y)$create_op <- list()
return(y)
}
a <- tensor(1:5)
# define a generic for sum
tensorsum <- function(x,y) UseMethod("tensorsum")
# define a sum method for tensor
tensorsum.tensor <- function(x,y) {
# calcluate the output
z <- x + y
# set attributes
attributes(z)$creators <- list(x = deparse(substitute(x)), y = deparse(substitute(y)) )
attributes(z)$create_op <- "sum"
# return the output
return(z)
}
tensorsum(a, a)
# define a generic for sum
tensorprod <- function(x,y) UseMethod("tensorprod")
# define a sum method for tensor
tensorprod.tensor <- function(x,y) {
# calcluate the output
z <- x * y
# set attributes
attributes(z)$creators <- list(x = deparse(substitute(x)), y = deparse(substitute(y)) )
attributes(z)$create_op <- "prod"
# return the output
return(z)
}
tensorprod(a,a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment