How to bind data with plot function?

dankelley
Thu, 10 Feb 2022 13:52:42 +0000
New to Julia

This is my first posting here, and I apologize if this is silly.

I am quite familiar with R, and a scheme I use there is to compute something and assign it a class, so that I can then define a plot generic. You can see that below. The idea of this is that the foo and plot.foo functions would normally go in a library, so that the user simply has to call that library and then execute the last two lines in my example.

My question is how this ought to be done in Julia. I sort of think what I want to do is to return a named tuple that perhaps holds x, y and a function named plot that does the plotting. Is that the recommended approach? I’m hoping to learn to write Julia in a way that will not just work, but also be familiar to users, and that means I’m hoping that someone can advise me on what is the “Julia way”.

# R code
foo <- function(x)
{
    res <- list(x=x, y=sin(x))
    class(res) <- "Foo"
    res
}
plot.Foo <- function(x)
{
    plot(x$x, x$y)
}

s <- foo(seq(0, 2*pi, pi/64))
plot(s)

4 posts - 3 participants