juliaでFunctorについて
Functorは、structを通常の関数のように扱いたい時に使われる。
下の例だと、fucntion a::structとすることで、あたかもstrunctを関数として扱うことができる。
例えば、ニューラルネットワークのAffine変換を考える。
module My
struct Affine
W
b
Affine(W, b) = new(W, b) #これはなくても動く。
end
# Functorはstruct(Affine)を関数のように扱う。xは引数。
function (a::Affine)(x)
a.W * x + a.b
end
end
using .My
Affine = My.Affine
keisan(W, b, x) = W * x + b
W = rand(2,3)
b = rand(2)
x = rand(3)
a = Affine(W, b);
@assert a(x) ≈ keisan(W, b, x)
juliaのFuctorは、pythonでいうと__call__に相当する。
class Goma:
def __init__(self, name):
self.name = name # "ごま"
def __call__(self, human): # "Azarashi"
print(f"Hello {human}, I am {self.name}")
g = Goma("ごま")
g("Azarashi")