Skip to content

Instantly share code, notes, and snippets.

@bquast
Created November 11, 2019 14:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bquast/4653082fd163e97b16e5ec4f1acd1cfb to your computer and use it in GitHub Desktop.
# 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