Julia handling void return type - julia

What is the best method for handling a Void type when it is returned by a function? The suggestions in http://docs.julialang.org/en/release-0.5/manual/faq/#how-does-null-or-nothingness-work-in-julia don't work.
A MWE (must be run from the REPL so Base.source_dir() returns Void):
julia> isempty(Base.source_dir())
ERROR: MethodError: no method matching start(::Void)
Closest candidates are:
start(::SimpleVector) at essentials.jl:170
start(::Base.MethodList) at reflection.jl:258
start(::IntSet) at intset.jl:184
...
in isempty(::Void) at ./iterator.jl:3
in isempty(::Void) at /Applications/Julia-0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
julia> isdefined(Base.source_dir())
ERROR: TypeError: isdefined: expected Symbol, got Void
julia> typeof(Base.source_dir()) == Void
true
This is on Julia 0.5. The latter option works, but it's a bit ugly.

Void is a singleton -- a type with exactly one instance.
That one instance is Void() also called nothing.
Be aware that nothing === Void()
You can treat it just like any other value.
It is returned by a bunch of functions, like println.
You can check if something has returned nothing -- ie and instance of type Void.
By
julia> println()===nothing
true
For the sake of type-stability,
a method should not return nothing some of the time, and something some of the time.
in those case it should instead return a Nullable,
generally.

Related

Java 8 Functional Programming - Passing function along with its argument

I have a question on Java 8 Functional Programming. I am trying to achieve something using functional programming, and need some guidance on how to do it.
My requirement is to wrap every method execution inside timer function which times the method execution. Here's the example of timer function and 2 functions I need to time.
timerMethod(String timerName, Function func){
timer.start(timerName)
func.apply()
timer.stop()
}
functionA(String arg1, String arg2)
functionB(int arg1, intArg2, String ...arg3)
I am trying to pass functionA & functionB to timerMethod, but functionA & functionB expects different number & type of arguments for execution.
Any ideas how can I achieve it.
Thanks !!
you should separate it into two things by Separation of Concerns to make your code easy to use and maintaining. one is timing, another is invoking, for example:
// v--- invoking occurs in request-time
R1 result1 = timerMethod("functionA", () -> functionA("foo", "bar"));
R2 result2 = timerMethod("functionB", () -> functionB(1, 2, "foo", "bar"));
// the timerMethod only calculate the timing-cost
<T> T timerMethod(String timerName, Supplier<T> func) {
timer.start(timerName);
try {
return func.get();
} finally {
timer.stop();
}
}
IF you want to return a functional interface rather than the result of that method, you can done it as below:
Supplier<R1> timingFunctionA =timerMethod("A", ()-> functionA("foo", "bar"));
Supplier<R2> timingFunctionB =timerMethod("B", ()-> functionB(1, 2, "foo", "bar"));
<T> Supplier<T> timerMethod(String timerName, Supplier<T> func) {
// v--- calculate the timing-cost when the wrapper function is invoked
return () -> {
timer.start(timerName);
try {
return func.get();
} finally {
timer.stop();
}
};
}
Notes
IF the return type of all of your functions is void, you can replacing Supplier with Runnable and then make the timerMethod's return type to void & remove return keyword from timerMethod.
IF some of your functions will be throws a checked exception, you can replacing Supplier with Callable & invoke Callable#call instead.
Don't hold onto the arguments and then pass them at the last moment. Pass them immediately, but delay calling the function by wrapping it with another function:
Producer<?> f1 =
() -> functionA(arg1, arg2);
Producer<?> f2 =
() -> functionB(arg1, arg2, arg3);
Here, I'm wrapping each function call in a lambda (() ->...) that takes 0 arguments. Then, just call them later with no arguments:
f1()
f2()
This forms a closure over the arguments that you supplied in the lambda, which allows you to use the variables later, even though normally they would have been GC'd for going out of scope.
Note, I have a ? as the type of the Producer since I don't know what type your functions return. Change the ? to the return type of each function.
Introduction
The other answers show how to use a closure to capture the arguments of your function, no matter its number. This is a nice approach and it's very useful, if you know the arguments in advance, so that they can be captured.
Here I'd like to show two other approaches that don't require you to know the arguments in advance...
If you think it in an abstract way, there are no such things as functions with multiple arguments. Functions either receive one set of values (aka a tuple), or they receive one single argument and return another function that receives another single argument, which in turn returns another one-argument function that returns... etc, with the last function of the sequence returning an actual result (aka currying).
Methods in Java might have multiple arguments, though. So the challenge is to build functions that always receive one single argument (either by means of tuples or currying), but that actually invoke methods that receive multiple arguments.
Approach #1: Tuples
So the first approach is to use a Tuple helper class and have your function receive one tuple, either a Tuple2 or Tuple3:
So, the functionA of your example might receive one single Tuple2<String, String> as an argument:
Function<Tuple2<String, String>, SomeReturnType> functionA = tuple ->
functionA(tuple.getFirst(), tuple.getSecond());
And you could invoke it as follows:
SomeReturnType resultA = functionA.apply(Tuple2.of("a", "b"));
Now, in order to decorate the functionA with your timerMethod method, you'd need to do a few modifications:
static <T, R> Function<T, R> timerMethod(
String timerName,
Function<? super T, ? extends R> func){
return t -> {
timer.start(timerName);
R result = func.apply(t);
timer.stop();
return result;
};
}
Please note that you should use a try/finally block to make your code more robust, as shown in holi-java's answer.
Here's how you might use your timerMethod method for functionA:
Function<Tuple2<String, String>, SomeReturnType> timedFunctionA = timerMethod(
"timerA",
tuple -> functionA(tuple.getFirst(), tuple.getSecond());
And you can invoke timedFunctionA as any other function, passing it the arguments now, at invocation time:
SomeReturnType resultA = timedFunctionA.apply(Tuple2.of("a", "b"));
You can take a similar approach with the functionB of your example, except that you'd need to use a Tuple3<Integer, Integer, String[]> for the argument (taking care of the varargs arguments).
The downside of this approach is that you need to create many Tuple classes, i.e. Tuple2, Tuple3, Tuple4, etc, because Java lacks built-in support for tuples.
Approach #2: Currying
The other approach is to use a technique called currying, i.e. functions that accept one single argument and return another function that accepts another single argument, etc, with the last function of the sequence returning the actual result.
Here's how to create a currified function for your 2-argument method functionA:
Function<String, Function<String, SomeReturnType>> currifiedFunctionA =
arg1 -> arg2 -> functionA(arg1, arg2);
Invoke it as follows:
SomeReturnType result = currifiedFunctionA.apply("a").apply("b");
If you want to decorate currifiedFunctionA with the timerMethod method defined above, you can do as follows:
Function<String, Function<String, SomeReturnType>> timedCurrifiedFunctionA =
arg1 -> timerMethod("timerCurryA", arg2 -> functionA(arg1, arg2));
Then, invoke timedCurrifiedFunctionA exactly as you'd do with any currified function:
SomeReturnType result = timedCurrifiedFunctionA.apply("a").apply("b");
Please note that you only need to decorate the last function of the sequence, i.e. the one that makes the actual call to the method, which is what we want to measure.
For the method functionB of your example, you can take a similar approach, except that the type of the currified function would now be:
Function<Integer, Function<Integer, Function<String[], SomeResultType>>>
which is quite cumbersome, to say the least. So this is the downside of currified functions in Java: the syntax to express their type. On the other hand, currified functions are very handy to work with and allow you to apply several functional programming techniques without needing to write helper classes.

Julia pass optional parameter to inner function call

I have something like the following
function test(; testvar=nothing)
# only pass testvar to function if it has a useful value
inner_function(testvar != nothing ? testvar2=testvar : # leave it out)
end
# library function, outside my control, testvar2 can't be nothing
function inner_function(; testvar2=useful value)
# do something
end
I know I can use if/else statements within test() but inner_function has lots of parameters so I would prefer to avoid that from a code duplication standpoint. Is this possible?
Note: inner_function cannot have testvar2 = nothing, if testvar2 is passed it has to have a valid value.
As #elsuizo points out, multiple dispatch is one of the core julia features which allows you to perform such operations. Find bellow a quick example:
>>> inner_func(x) = true;
>>> inner_func(::Type{Void}) = false;
Note: it seems Nothing has been renamed to Void (as a warning prompts out when I try to use it).
inner_func has 2 method definitions, if Void is passed as a parameter, the function will just return false (change this behaviour by do nothing or whatever you want to do). Instead, if the function receives anything else than Void, it will just do something else (in this case, return true).
Your test wouldn't have to perform any check at all. Just pass the parameters to the inner_func, and it will decide what to do (which of the 2 methods of the function inner_func to call) depending on the parameter type.
An example:
>>> a = [1, 2, 3, Void, 5];
>>> filter(inner_func, a)
4-element Array{Any,1}:
1
2
3
5
For the numerical elements, the function calls the method of the function that returns true, and thus, the numerical elements are returned. For the Void element, the second method of the function is called, returning false, and thus, not returning such element.

Can I build a parameterless constructor for a parametric type in an outer constructor?

In order to instantiate a type like x = MyType{Int}()
I can define a inner constructor.
immutable MyType{T}
x::Vector{T}
MyType() = new(T[])
end
Is it possible to achieve the same objective using an outer constructor?
This can be done using the following syntax:
(::Type{MyType{T}}){T}() = MyType{T}(T[])
The thing in the first set of parentheses describes the called object. ::T means "of type T", so this is a definition for calling an object of type Type{MyType{T}}, which means the object MyType{T} itself. Next {T} means that T is a parameter of this definition, and a value for it must be available in order to call this definition. So MyType{Int} matches, but MyType doesn't. From there on, the syntax should be familiar.
This syntax is definitely a bit fiddly and unintuitive, and we hope to improve it in a future version of the language, hopefully v0.6.
I may be wrong, but if you cannot build parameterless function like this:
julia> f{T}() = show(T)
WARNING: static parameter T does not occur in signature for f at none:1.
The method will not be callable.
f (generic function with 1 method)
therefore you won't be able to do this:
julia> immutable MyType{T}
x::Vector{T}
end
julia> MyType{T}() = MyType{T}(T[])
WARNING: static parameter T does not occur in signature for call at none:1.
The method will not be callable.
MyType{T}
julia> x = MyType{Int}()
ERROR: MethodError: `convert` has no method matching convert(::Type{MyType{Int64}})
...
Every outer constructor is also a function.
You can say
f(T::Type) = show(T)
and also
MyType(T::Type) = MyType(T[])
But julia needs to see the type in the call to know which you want.

evaluate null object -> nashorn console crash ("Cannot get default string value")

I'm new to JavaScript. In nashorn 1.8.0_11 I see the behavior below. Note print(x) works fine yet evaluating x causes a crash. May I consider this a bug? If so, is it a known bug?
jjs> var x = Object.create(null);
jjs> print(x);
<shell>:1 TypeError: Cannot get default string value
jjs> x;
Exception in thread "main" ECMAScript Exception: TypeError: Cannot get default string value
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:56)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:212)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:184)
at jdk.nashorn.internal.objects.Global.getDefaultValue(Global.java:592)
at jdk.nashorn.internal.runtime.ScriptObject.getDefaultValue(ScriptObject.java:1257)
at jdk.nashorn.internal.runtime.JSType.toPrimitive(JSType.java:256)
at jdk.nashorn.internal.runtime.JSType.toPrimitive(JSType.java:252)
at jdk.nashorn.internal.runtime.JSType.toStringImpl(JSType.java:993)
at jdk.nashorn.internal.runtime.JSType.toString(JSType.java:326)
at jdk.nashorn.tools.Shell.readEvalPrint(Shell.java:449)
at jdk.nashorn.tools.Shell.run(Shell.java:155)
at jdk.nashorn.tools.Shell.main(Shell.java:130)
at jdk.nashorn.tools.Shell.main(Shell.java:109)
This is as expected. When you evaluate expressions interactively with "jjs" shell tool, it converts evaluated expression result as String to print the same. Also, "print" function calls toString on object to print string representation of it to console. With Object.create(null), you are creating an object whose prototype is null (and hence does not inherit Object.prototype.toString). Also, your object does not have "toString" property with function typed value and hence the TypeError. Please note that you can similar behaviour with v8 shell as well.
V8 version 3.25.15 [sample shell]
var x = Object.create(null)
x;
print(x)

How to implement generic Max<TSource>(Func<TSource,TSource> func)

I am busy writing my own collection type and need to have a function
Max that returns the value in the collection, where one of the value attributes is a max or some condition holds.
So I am trying to call Max(Func<...) on one of the underlying .net collections, but
I can't seem to get it to work:
public TValue MaxValue(Func<TValue,TValue> func)
{
return this.valueSet.Max<TValue>(func);
}
but I am getting 2 errors:
Argument 2: cannot convert from 'System.Func<TValue,TValue>' to System.Func<TValue,int>'
and
'System.Collections.Generic.SortedSet<TValue>' does not contain a definition for 'Max'
and the best extension method overload 'System.Linq.Enumerable.Max<TSource>(System.Collections.Generic.IEnumerable<TSource>,
System.Func<TSource,int>)' has some invalid arguments
I just can't seem to figure out what I should be doing here...
When you call:
this.valueSet.Max<TValue>(func);
the compiler interprets this as one of the Max overloads with one generic type. Either explicitly point out that the return value also should be a TValue type:
this.valueSet.Max<TValue, TValue>(func);
or use implicit typing and let the compiler sort out the types itself:
this.valueSet.Max(func);

Resources