関数型 - ラムダ関数

 
次の計算を、ラムダ関数(匿名関数、無名関数)を使用して書く。
  • 2 * 3 = 6
Scheme  Gauche 0.8
$ gosh
gosh> ((lambda (x y) (* x y)) 2 3)
6
gosh> (exit)

➢ 簡略化できる
$ gosh
gosh> (* 2 3)
6
gosh> (exit)

Haskell  GHC 6.10
$ ghci
Prelude> (\ x y -> x * y) 2 3
6
Prelude> :q

➢ 簡略化できる
$ ghci
Prelude> (*) 2 3
6
Prelude> :q

Erlang  5.6
$ erl
1> fun (X, Y) -> X * Y end (2, 3).
6
2> q().

Scala  2.7
$ scala
scala> ((x:Int, y:Int) => x * y)(2, 3)
res0: Int = 6
scala> :q

OCaml  3.10
$ ocaml
# (fun x y -> x * y) 2 3;;
- : int = 6
# #quit;;

➢ 簡略化できる
$ ocaml
# ( * ) 2 3;;
- : int = 6
# #quit;;

R  2.8
$ R
> (function(x, y) x * y)(2, 3)
[1] 6
> q()

➢ 簡略化できる
$ R
> "*" (2, 3)
[1] 6
> q()

JavaScript  1.8
$ js
js> (function(x, y) x * y)(2, 3);
6
js> quit();

Ruby  1.9
$ irb --prompt simple
>> -> x, y { x * y }.(2, 3)
=> 6
>> lambda { |x, y| x * y }.(2, 3)
=> 6
>> quit

Python  3.0, 2.5
$ python
>>> (lambda x, y: x * y)(2, 3)
6
>>> quit()

PHP  5.3
$ php -a
php > print
php > call_user_func(
php (     function($x, $y) { return $x * $y; },
php (     2, 3);
6

➢ ここで、次のような記法は使用できない。
php > print
php > (function($x, $y) { return $x * $y; })(2, 3);
Parse error: syntax error, unexpected '(' in php shell code on line 2

➢ call_user_func を使用したくなければ、一旦変数に代入してから呼び出す。
php > $foo = function($x, $y) { return $x * $y; };
php > print $foo(2, 3);
6
php > quit

更新履歴

日付 内容
2009-03-28 追加 OCaml
2009-03-10 追加 Erlang
2009-03-09 追加 Scheme
2009-03-05 追加 Scala
変更 PHP 5.2 → 5.3
2008-10-31 追加 R
2008-04-27 初版 Haskell, JavaScript, Ruby, Python, PHP