Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias quit() to quit?

Tags:

julia

This is just a convenience but I think useful. Note that IPython allows a pure quit as does Matlab. Thus it would be reasonble in Julia to allow aliasing.

Thanks for any ideas as to how to do this.

like image 957
comer Avatar asked Aug 20 '14 15:08

comer


2 Answers

Quitting in Julia

If you are using Julia from the command line then ctrl-d works. But if your intention is to quit by typing a command this is not possible exactly the way you want it because typing quit in the REPL already has a meaning which is return the value associated with quit, which is the function quit.

julia> quit
quit (generic function with 1 method)

julia> typeof(quit)
Function

Also Python

But that's not rare, for example Python has similar behavior.

>>> quit
Use quit() or Ctrl-D (i.e. EOF) to exit

Using a macro

Using \q might be nice in the Julia REPL like in postgres REPL, but unfortunately \ also already has a meaning. However, if you were seeking a simple way to do this, how about a macro

julia> macro q() quit() end

julia> @q

Causes Julia to Quit

If you place the macro definition in a .juliarc.jl file, it will be available every time you run the interpreter.

like image 60
waTeim Avatar answered Oct 11 '22 22:10

waTeim


As waTeim notes, when you type quit into the REPL, it simply shows the function itself… and there's no way to change this behavior. You cannot execute a function without calling it, and there are a limited number of ways to call functions in Julia's syntax.

What you can do, however, is change how the Functions are displayed. This is extremely hacky and is not guaranteed to work, but if you want this behavior badly enough, here's what you can do: hack this behavior into the display method.

julia> function Base.writemime(io::IO, ::MIME"text/plain", f::Function)
           f == quit && quit()
           if isgeneric(f)
               n = length(f.env)
               m = n==1 ? "method" : "methods"
               print(io, "$(f.env.name) (generic function with $n $m)")
           else
               show(io, f)
           end
       end
Warning: Method definition writemime(IO,MIME{symbol("text/plain")},Function) in module Base at replutil.jl:5 overwritten in module Main at none:2.
writemime (generic function with 34 methods)

julia> print # other functions still display normally
print (generic function with 22 methods)

julia> quit # but when quit is displayed, it actually quits!

$

Unfortunately there's no type more specific than ::Function, so you must completely overwrite the writemime(::IO,::MIME"text/plain",::Function) definition, copying its implementation.

Also note that this is pretty unexpected and somewhat dangerous. Some library may actually end up trying to display the function quit… causing you to lose your work from that session.

like image 26
mbauman Avatar answered Oct 11 '22 23:10

mbauman