匿名関数

2026年3月17日
1 分

Julia には匿名関数もある。 ちょっと JavaScript に構文が似てる。

julia> square = x -> x * x
#2 (generic function with 1 method)

julia> square(3)
9

map のような高階関数の引数に使える。

julia> array = [1,2,3]
3-element Vector{Int64}:
 1
 2
 3

julia> map(square, array)
3-element Vector{Int64}:
 1
 4
 9

変数に代入せず、直接書いてもいい。

julia> map(x -> x * x, array)
3-element Vector{Int64}:
 1
 4
 9

関数の本体部分が複数行になる場合は、beginend で囲む(下の例では1行しかないけど)。

julia> cubic = x -> begin
         x * x * x
       end
#26 (generic function with 1 method)

julia> cubic(3)
27