2
1

More than 1 year has passed since last update.

知っていて当たり前-16 ラムダ関数

Posted at

知っていて当たり前-16 ラムダ関数

匿名関数,無名関数,λ関数,ラムダ関数などと言語ごとにいろいろな名前で呼ばれている。

x -> x * 1.08
#1 (generic function with 1 method)

これだけだと,実行できない。引数を与えるには以下のようにするが,メリットが見えない。

(x -> x * 1.08)(100)
108.0
(x -> x * 1.08).([100, 200, 300])
3-element Vector{Float64}:
 108.0
 216.0
 324.0

ラムダ関数を変数に代入すると,その変数は関数名になる。

price = x -> x * 1.08
#7 (generic function with 1 method)
price(100), price(200)
(108.0, 216.0)
price.([100, 200, 300])
3-element Vector{Float64}:
 108.0
 216.0
 324.0

しかしこれはラムダ関数の説明にはなっていない。以下の price2 は関数定義であり,同じ結果になる。

price2(x) = x * 1.08
price2(100), price2(200)
(108.0, 216.0)
price2.([100, 200, 300])
3-element Vector{Float64}:
 108.0
 216.0
 324.0

引数に関数を取る関数の場合ラムダ,関数として既存の関数,関数定義による関数と同時に,ラムダ関数も指定できる。

map(price2, [100, 200, 300])
3-element Vector{Float64}:
 108.0
 216.0
 324.0
map(x -> x*1.08, [100, 200, 300])
3-element Vector{Float64}:
 108.0
 216.0
 324.0
filter(x -> x > 5, [3, 4, 5, 6, 7])
2-element Vector{Int64}:
 6
 7
foreach(x -> print("$x "), rand(1:10, 5))
10 6 9 3 1 
x = 1; y = 2
arg = "x"
a = Meta.parse("func2($arg) = x + y")
eval(a)
func2 (generic function with 1 method)
func2(5)
7

複数行の場合は、beginend で囲む。

nebiki = x -> begin
    price = x * 0.9
    return price * 1.08
end

nebiki(100)
97.2

複数の引数を持つ場合には引数をタプルで示す。

func = (x, y) -> 2x + 3y
func(10, 20)
80
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1