Skip to content
Prev 387185 / 398503 Next

Is it Possible to Create S4 Function Objects?

It appears that my previous post may lack clarity.

So, I've created three examples of mathematical function objects.
(One) using a standard closure with lexical scoping, (two) using S3
with an attribute and (three) using S4 with a slot.
Each example constructs the function object via a constructor (of some
form), plots it, then prints the attribute/etc.
However, the third example with S4 is incomplete.

Any suggestions welcome.

----begin code----

plotf <- function (f)
{   x <- seq (-1, 1,, 200)
    plot (x, f (x), type="l")
}

#standard closure, with lexical scoping
quad.lex <- function (p = c (0, 0, 1) )
{   function (x)
        p [1] + p [2] * x + p [3] * x^2
}

#s3-based function object, with attribute
quad.s3 <- function (p = c (0, 0, 1) )
{   f <- function (x)
    {   this <- sys.function ()
        p <- attr (this, "p")
        p [1] + p [2] * x + p [3] * x^2
    }
    attr (f, "p") <- p
    f
}

#s4-based function object, with slot
setClass ("Quad.S4", slots = list (p="numeric") )
Quad.S4 <- function (p = c (0, 0, 1) )
{   #?
}

f.lex <- quad.lex ()
plotf (f.lex)
environment (f.lex)$p

f.s3 <- quad.s3 ()
plotf (f.s3)
attr (f.s3, "p")

f.s4 <- Quad.S4 ()
#plotf (f.s4)
#f.s4 at p


On Sat, Feb 13, 2021 at 10:53 AM Abby Spurdle (/??bi/)
<spurdle.a at gmail.com> wrote: