Function wrapper with parameterse from struct

Dear all,
I’m trying to figure out how to nicely wrap my function into a struct (or possible other type), which holds all the parameters I want to set before the function is called.
The idea around that is that I’m passing an array of this struct into another function which should than only care about one argument of the function. This other function expects:

Array{Function,1}

My first idea was to just wrap-up the function with another function like this:

function spin_up3(psi::Union{Array{Complex{Float64},1},Array{Float64,1}})::Function
        number_operator!(H::Hubbard, psi, 1,1)
    end

and than fill the array with spin_up3 and similar functions. That worked fine until I used an array of length 1

[spin_up3]

when Julia didn’t recognice the Type as Function but as typeof{spin_up3} and threw me a typeassert error because typeof{spin_up3} didn’t seem to be a Function.

What I would like to have is something like that,

struct SpinOperator  <: Operator
    state::Int
    sigma::Int
   

    act = function act(psi::Union{Array{Complex{Float64},1},Array{Float64,1}})::Function
        number_operator!(H::Hubbard, psi, state,sigma)
    end
    SpinOperator(state::Int, sigma::Int) = new(state, sigma)
end

which calls the Function defined for act with the parameters state and sigma, which are set when the struct is created
When I try to run the current code I get a LoadError because he complains that he doesn’t have the field act.

I would really appreceate your help on that!

You can make the Struct callable it self:

struct SpinOperator  <: Operator
    state::Int
    sigma::Int
    SpinOperator(state::Int, sigma::Int) = new(state, sigma)
end

function (act::SpinOperator)(psi::Union{Array{Complex{Float64},1},Array{Float64,1}})
        number_operator!(H::Hubbard, psi, act.state, act.sigma)# EDIT:  typo
end

# Use it like this
function foo(s::SpinOperator)
   return s([42])
end

1 Like

You could always (for your first approach) have a function like

function fArray(fs...)
    A = Array{Function,1}()
    for f in fs
       push!(A, f)
    end
   return A
end

then:

julia> fArray(sin, cos, tan)
3-element Array{Function,1}:
 sin (generic function with 13 methods)
 cos (generic function with 13 methods)
 tan (generic function with 12 methods)

julia> fArray(sin)
1-element Array{Function,1}:
 sin (generic function with 13 methods)
1 Like