Nice way to display functions


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

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

update: use show instead of display


Don’t override display, override show:


I would use something like:

immutable ShortFun{T<:Function}
# This printing could be made nicer by removing the `begin` that appears. See MacroTools, 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)))))
f = @shortfun x -> 2+x


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., x::mytype) = print(io, "mytype: ", code_lowered(x.f)[1])
function, m::MIME"text/plain", x::mytype)
    print(io, "mytype:\n")
    show(io, m, code_lowered(x.f)[1])

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.)


See also the discussion in


what about:

type mytype

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

feels like R


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.


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