変数と関数の構造体としての定義

Juliaを用いて変数と関数を構造体として定義する.これはオブジェクト指向におけるクラス化に相当する.

#構造体として定義
struct Variable
data::Any
end

#Functionを抽象型として定義
abstract type Function end

#(f::Function) は関数呼び出しの引数の型制約
#fはFunction型またはそのサブ型でなければならない
#(input::Variable) は関数の引数inputがVariable型
#でなければならないことを示す型制約
#begin ... end の部分で関数呼び出し時に実行されるコードブロックを定義
(f::Function)(input::Variable)= begin
x = input.data
y = forward(f, x)
output = Variable(y)
return output
end

#抽象型 Function に対する forward メソッドの基底実装を与えることで,
#全ての具象サブ型に対して forward が定義される必要があることを強制する
forward(f::Function, x) = error("forward is not implemented")

#Functionののサブ型Squareとして具体的な関数を定義
struct Square <: Function end

#::Square は型パラメータで,このメソッドが Square 型のオブジェクトに
#対して呼び出された時に適用される
#Juliaでは、同じ関数名でも引数の型が異なれば異なる関数が呼び出される.
#これは多重ディスパッチ(multiple dispatch)という.
forward(::Square, x) = x^2

x = Variable(10)
f = Square()
y = f(x)

println(y.data)

なお,::Anyは型注釈で data::Any はdataフィールドが整数,浮動小数点数,文字列,カスタム型のオブジェクトなど,何らかの型の値を持つことができることを意味している.

アウトプットは以下のようになる.

100

Mathematics is the language with which God has written the universe.





















ガンマ関数 数値微分 t分布の正規分布近似 マトリョーシカ特徴表現学習 LISA BitNet b1.58