检查函数的参数是否是函数

Ben*_*lop 2 parameters singleton function typeof julia

我有一个功能:

function f(a)
   do something that depends on a
end
Run Code Online (Sandbox Code Playgroud)

哪种行为取决于参数a。这可以是字符串、整数或函数本身。为此,我想检查参数本身是否是函数。

function f(a)
   if typeof(a) == int
      ...
   end
   ...
end
Run Code Online (Sandbox Code Playgroud)

我尝试使用typeof(a). 如果a是一个函数,我得到:

typeof(a) (singleton type of function a, subtype of Function)
Run Code Online (Sandbox Code Playgroud)

但如果我然后使用:

typeof(a) == Function
Run Code Online (Sandbox Code Playgroud)

这是false

Dan*_*etz 6

您还可以考虑使用 Julia 的多重调度功能:

function f(x::Function)
  # do something with a Function
end

funcion f(x::Int)
  # do something with an Int
end
Run Code Online (Sandbox Code Playgroud)

而不是在函数内部使用条件。

如果编译器可以在编译时进行类型推断并且更加朱利安,那么这样做的好处是速度更快。


sj9*_*126 5

您可以使用isa()此用途。一个简单的例子:

julia> f(x) = x
f (generic function with 1 method)

julia> isa(f, Function)
true
Run Code Online (Sandbox Code Playgroud)

isa也可以用作中缀运算符:

julia> f isa Function
true
Run Code Online (Sandbox Code Playgroud)