use*_*974 6 functional-programming julia typesafe
比方说,我想将一个函数传递给另一个函数:
function foo()
return 0;
end
function bar(func)
return func();
end
print(bar(foo));
Run Code Online (Sandbox Code Playgroud)
但你可以使函数类型安全:
function func(t::Int)
print(t);
end
func(0); #produces no error
func("Hello world"); #produces an error
Run Code Online (Sandbox Code Playgroud)
我没有发现如何将两者结合起来,这意味着我如何显式定义 的参数bar
,例如func
,作为一个函数,可能具有某些输入/输出参数类型。
预先感谢您的任何帮助。
函数的类型为Function
。您可以轻松检查:
julia> foo() = 1;
julia> T = typeof(foo)
typeof(foo)
julia> supertype(T)
Function
julia> foo isa Function
true
Run Code Online (Sandbox Code Playgroud)
这不一定涵盖所有可调用类型,因为您可以使任何类型可调用:
julia> struct Callable end
julia> (::Callable)(x::Number) = x + one(x)
julia> callable = Callable()
Callable()
julia> callable(5)
6
julia> callable isa Function
false
Run Code Online (Sandbox Code Playgroud)