Le mardi 06 janvier 2015 à 09:25 -0800, James Crist a écrit :
> I'm trying to replicate the interface of some MATLAB code I use
> frequently. Because functions in MATLAB have knowledge of their
> "output arguments", different behaviors can occur if an assignment is
> used or not (i.e. `a = foo()` can do something different than just
> `foo()`). Specifically, the interface I'm trying to replicate displays
> a plot with no output arguments, and otherwise returns the data. 
> 
> In Python, I'd use a kwarg `plot=False`. What's the most Julian way of
> doing this? I have two thoughts right now:
> 
> 1. Use a kwarg. `foo(...)` returns the data, `foo(..., plot=true)`
> creates a plot and returns nothing (or the plot handle?).
> 
> 2. Create a `@plot` macro that sets a global `PLOT` boolean variable.
> This indicates to the functions it's configured to work with that the
> data should be plotted. The use would be: `@plot foo(...)`, which
> generates the code:
> ```
> PLOT = true
> foo(...)
> PLOT = false
> ```
> This could also be modified to return the plot handle at the end of
> the block. While I tend to like this interface more than #1, it's also
> more magical, which is bad.
> 
> 3. Create a `@plot` macro that somehow knows how to plot each function
> (a registry of some kind?). Then the function needs no knowledge of
> how to plot itself, and the macro is just a fast way of writing in the
> plotting code. Use is `@plot foo(...)`, which expands to
> ```
> data = foo(...)
> plotting code here...
> ```
> 
> 4. Create a separate function `fooplot`. `foo` returns the data.
> `fooplot` runs foo, and creates a plot.
> 
> Out of all of these, I like option #3 best, but want to use the most
> Julian way of doing things as possible. Thoughts?
If your function can return data instead of plotting it, a possibly more
elegant design would be to make it return a custom type that would
implement a `plot` method. That way you could do either:
a = foo(...)
plot(a)

or
plot(foo(...))

which is as short as
foo(..., plot=true)
and
@plot foo(...)


Depending on the kind of data you need to return, it could be e.g. a
very simple type wrapping an array. Unfortunately, AFAIK there is no
easy way currently to inherit all methods from the array in your custom
type, but it may become easier in the future (and APIs need to be
forward-looking). See https://github.com/JuliaLang/julia/pull/3292


> ------
> 
> Also, is there a good way to only load the plotting package (Gadfly,
> Winston, etc...) when it's first used? Loading these takes a long
> time; it would be nice if they could only be loaded upon the first
> call to `plot`.
This has been discussed several times on the list, though I'm not sure
what the most up-to-date reply is.



Regards

Reply via email to