How to type annotate functions which take functions as args

Alternatively if you just want your function h to call any function passed, not just f (which is presumably the case since otherwise you wouldn’t have it as an argument and just fixed in the code) you can use the ::Function annotation. (I don’t know Haskell so I can’t tell if that’s what you are trying to do.) For example,

julia> function h(_f::Function, x::Number)
           return g(_f(x))
       end
h (generic function with 1 method)

julia> supertype(typeof(f))
Function

julia> f isa Function
true

julia> g isa Function
true

That said, it’s often useful not to restrict functions to subtypes of Function since there are other ways of creating objects that you can call. For example, you can have a callable struct.

struct MyStruct
    a::Float64
end

function (mystruct::MyStruct)(b::Number)
    mystruct.a + b
end

julia> astruct = MyStruct(1.2)
MyStruct(1.2)

julia> astruct(3)
4.2

julia> astruct isa Function
false

As such, I tend to leave off function annotations and just try calling whatever is passed. (Cf. duck typing.)

3 Likes