mapとfilterとリスト内包
PHP
<?php $result = array_map( create_function('$x', 'return pow(2,$x);'), range(0, 10) ); $result2 = array_filter( range(0, 10), create_function('$x', 'return $x&1;') ); print_r( $result ); print_r( $result2 ); ?>
Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 8 [4] => 16 [5] => 32 [6] => 64 [7] => 128 [8] => 256 [9] => 512 [10] => 1024 ) Array ( [1] => 1 [3] => 3 [5] => 5 [7] => 7 [9] => 9 )
LINQ(C#)
Enumerable.Range(0, 11).Select(x => (int)Math.Pow(2, x)).ToList().ForEach(Console.WriteLine); var seq = from x in Enumerable.Range( 0, 11 ) where (x & 1) == 1 select x; seq.ToList().ForEach( Console.WriteLine );
出力はご妄想にお任せします(割愛)。
Python
>>> map( lambda x: 2**x, range( 11 ) ) [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] >>> filter( lambda x: x&1, range( 11 ) ) [1, 3, 5, 7, 9] # list comprehensions >>> [ 2**x for x in range( 11 ) ] [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] >>> [ x for x in range( 11 ) if x&1 ] [1, 3, 5, 7, 9]
Common Lisp
map系関数と変態loopマクロ。(d:id:Nobuhisa:20071204:1196774442)
CL-USER > (mapcar #'(lambda (x) (expt 2 x)) (loop for x from 0 to 10 collect x)) (1 2 4 8 16 32 64 128 256 512 1024) ;; 列関数バージョン(大差ない) CL-USER > (map 'list #'(lambda (x) (expt 2 x)) (loop for x from 0 to 10 collect x)) (1 2 4 8 16 32 64 128 256 512 1024) CL-USER > (mapcan #'(lambda (x) (if (oddp x) (list x))) (loop for x from 0 to 10 collect x)) (1 3 5 7 9) ;; loop(これはリスト内包表記と呼んでいいのかな??) CL-USER > (loop for x from 0 to 10 collect (expt 2 x)) (1 2 4 8 16 32 64 128 256 512 1024) CL-USER > (loop for x from 0 to 10 when (plusp (logand x 1)) ;x&1が1以上か collect x) (1 3 5 7 9) CL-USER > (loop for x from 0 to 10 when ((lambda (x) (oddp x)) x) ;↑のoddpバージョン collect x) (1 3 5 7 9)
Haskell
-- ラムダ式で Prelude> map (\x -> round (2**x)) [0..10] [1,2,4,8,16,32,64,128,256,512,1024] -- 関数合成で Prelude> map (round . (2**)) [0..10] [1,2,4,8,16,32,64,128,256,512,1024] Prelude> filter odd [0..10] [1,3,5,7,9] -- list comprehensions Prelude> [ round (2**x) | x <- [0..10] ] [1,2,4,8,16,32,64,128,256,512,1024] Prelude> [ x | x <- [0..10], odd x ] [1,3,5,7,9] --ビット演算知らなかったのでついでに調べた Prelude> import Data.Bits Prelude Data.Bits> [ x | x <- [0..10], ((x::Int).&.1)==1 ] [1,3,5,7,9]
F#(Ocaml)
結構苦戦した。。
> List.map (fun x -> int_of_float( Math.Pow(2.0, float_of_int(x)) )) [0..10];; val it : int list = [1; 2; 4; 8; 16; 32; 64; 128; 256; 512; 1024] > List.filter (fun x -> x &&& 1 = 1) [0..10];; val it : int list = [1; 3; 5; 7; 9] (* list comprehensions *);; > let seq = { for x in 0..10 - -> int_of_float( Math.Pow(2.0, float_of_int(x)) ) };; > { for x in 0..10 - when x &&& 1 = 1 - -> x };; val it : seq<int> = seq [1; 3; 5; 7; ...]
map系とリスト内包では戻り値の型が違うみたい。
訂正:
いげ太さんにコメントもらいました。
勉強してから再掲します。今日は眠いのでとりあえず寝ます・・・
Erlangもやろうかと思ったけど疲れたからやめた。