Pascal procedure sumofsequence var i s integer begin
手続きプログラミングの例 任意個数の整数の和を求めるPascalプログラム procedure sum_of_sequence ; var i, s : integer ; begin s : = 0 ; while i < > -9999 do begin readline(i) ; s : = s+i ; end ; write(s) ; end ;
関数型プログラミングの利点 ; データとコード (+ 1 3) ; ==>4 '(+ 1 3) ; ==>(+ 1 3) (eval '(+ 1 3)) ; ==>4 (eval (cons '+ '(1 3))) ; ==>4 ; データとしての関数 (lambda (x) (* x x)) ; ==>(lambda (x) (* x x)) (funcall (lambda (x) (* x x)) 3) ; ==>9 (setq two-times '(lambda (x) (* x x))) ; ==>(lambda (x) (* x x)) (funcall two-times 3) ; ==>9 (fset 'ftwo-times) (ftwo-times 3) ; ==>9
ユーザ定義クラスの演算の例 /* "Complex. java" 複素数(和と積を実装) */ public class Complex{ double real, image; //実部と虚部 //wと成す角(wから計る) double angle(Complex w){ double ang=Math. atan 2(image, real); double ang_w=Math. atan 2(w. image, w. real); return ang-ang_w; } //コンストラクタ:パラメタは実部と虚部 Complex(double r, double i){ real=r; image=i; } //和:パラメタの複素数に自分を加えて返す。 Complex plus(Complex w){ return new Complex(real+w. real, image+w. image); } //積:パラメタの複素数に自分を掛けて返す。 Complex times(Complex w){ return new Complex(real*w. real-image*w. image, //値表示(テスト用) void print(){ System. out. println(real+"+"+image+"i"); } //テスト public static void main(String[] args){ Complex z 1, z 2; z 1=new Complex(2. 3, 4. 7); z 2=new Complex(3. 0, 12. 8); z 1. plus(z 2). print(); z 1. times(z 2). print(); } real*w. image+image*w. real); } }
関数型とオブジェクト指向 クロージャ(Common. Lisp)は関数を実行する環境ごと保持する。 (defun generate-num () (let ((n 0)) #'(lambda () (prog 1 n (setq n (+ n 1)))))) (setq counter (generate-num)) (funcall counter) ; ==>0 (funcall counter) ; ==>1
- Slides: 12