Nice way to display functions


#1

i have a type that takes an anonymous function and want nice output for the display function.
The anonymous functions should be really short, so showing the source or some kind of compressed syntax tree would be an option.

type mytype
    f :: Function
end

function show(io::IO, x::mytype)
    println(io, "mytype")
    display(io, x.f)
end

update: use show instead of display


#2

Don’t override display, override show: https://docs.julialang.org/en/latest/manual/types/#Custom-pretty-printing-1


#3

I would use something like:

immutable ShortFun{T<:Function}
    f::T
    expr
end
# This printing could be made nicer by removing the `begin` that appears. See MacroTools
Base.show(io::IO, sf::ShortFun) = print(io, sf.expr)
# Beware that kwargs will make this slow; remove them if you don't need them
# and performance is a concern
(sf::ShortFun)(args...; kwargs...) = sf.f(args...; kwargs...)
macro shortfun(expr)
    esc(:(ShortFun($expr, $(Expr(:quote, expr)))))
end
f = @shortfun x -> 2+x

#4

You could output code_lowered(f)[1], i.e. the code for the first method of f (likely the only method if f is an anonymous function). e.g.

Base.show(io::IO, x::mytype) = print(io, "mytype: ", code_lowered(x.f)[1])
function Base.show(io::IO, m::MIME"text/plain", x::mytype)
    print(io, "mytype:\n")
    show(io, m, code_lowered(x.f)[1])
end

Here, I wrote distinct 2- and 3-argument show functions because only in the 3-argument (multiline) case does code_lowered(x.f)[1] show the actual lowered code.

(As far as I know, the non-lowered code, i.e. the user’s exact input, is not actually saved unless you do something like the macro trick suggested in another post.)

(Note: show should not call display, since display does not take an io parameter.)


#5

See also the discussion in https://github.com/JuliaLang/julia/issues/2625


#6

what about:

type mytype
    f::Function
    s::String
end

mytype(x::String) =  mytype(eval(parse(x)), x)
Base.show(io::IO, x::mytype) = print(io, x.s)

feels like R


#7

If it works for you, go for it. The main issue is that it won’t work for closures, but maybe you don’t need that.


#8

it’s just for aesthetics, thanks for the input!