What is the "NULL" function?


dear julia wizards: What is the equivalent of the NULL function to use as a default assignment when typing a function as an argument? by analogy, consider this first:

julia> work(x::Float64=NaN)= ( println("entering"); (!isnan(x)) && println("your x is $x") )

julia> work(1.0)  ## with argument
your x is 12.2

julia> work()   ## ok, my default

So, I want to do the same, but passing a function and not a Float.

julia> work(f::Function)= ( println("entering"); println("applying f to 4.0: ", f(4.0)) );

julia> work(sqrt)   ## with argument
applying f to 4.0: 2.0

julia> work()   ## this is what I want to enable.  a default
   --- so, here I want to see `entering\n` and then an error

after f::Function, I need to put a default argument, something like =nothing. but nothing is not right, because work() no longer even prints entering.

what is the magic NULL, NADA, nothing, etc., that one would typically use here? (I could define my own pointer to a nothing function as an alternative.)



Can’t you just define

work() = error()

in addition to work(f::Function)?


yes, in this specific context, I could do this. however, this was just an illustrative example. this is really a more general question.

but maybe “error()” is indeed a good convention function to ab-use as the null function if there is no other.

function work(f::Union{Function, Void} = nothing)
    f === nothing && error("did not give a function") 
    println("applying f to 4.0: ", f(4.0))
julia> work()
ERROR: did not give a function
 [1] work at ./REPL[4]:3 [inlined]
 [2] work() at ./REPL[4]:2

julia> work(identity)
applying f to 4.0: 4.0


What is the default function that you want? nothing is not a function.

  • If you want the default function to be the identity, then use work(f::Function=identity).
  • If you want the default function be one that returns nothing, do work(f::Function=x->nothing).
  • If you want to do something completely different when the user doesn’t pass a function, define a separate work() = ... function.
  • If you want to throw an error, don’t give any default or work() definition at all — by default it will throw a MethodError.

Passing NULL for missing arguments is a C idiom; although you can force this in Julia with a Union argument type, it’s probably better to re-think what you are doing. In many cases where you would pass a NULL function and have an explicit if (function == NULL) check in C you would use multiple dispatch (i.e. define different methods) in Julia or else define a default function that actually does what you want.