프로그래밍언어론 2023-04-06 수업정리

Flow

Scheme(2)


3.30 Scheme에서 이어짐

Eval - Apply

Defining Values

Input and Output

(define num(read)) // 입력 받은 후 출력
(write (+ num 1)) // num+1 출력 
(display (+ num 1)) // num+1 출력
(wirte "Hello \n World!") // "Hello \n World!" 출력
(display "Hello \n World!") // 표준 출력으로 따음표 없이 Hello -> 개행 -> World 출력

List

(cons 1 '(2 3)) // (1 2 3)
(list 1 2 3) // (1 2 3)
(car (list 1 2 3)) // 1
(cdr '(a b c)) // (b c)
(pair? (list 1 2 3)) // #t
(null? '()) // #t
(define atom?
  (lambda (x)
	  (and (not (pair? x)) (not (null? x)))))
(atom? 3) // #t
(atom? '()) // #f

quote

(1 2 3) // error
(quote (1 2 3)) // (1 2 3)
(atom? (quote (1 2 3))) // #f
(atom? (quote ())) // #f
(atom? '(1 2 3)) // #f
(atom? 'Scheme) // #t
(quote 1) // 1
'1 // 1
(quote '1) // '1

Predicates

(exact? 3.0) // #f
(exact? 1/2) // #t
(integer? 1.0) // #t

Comparison Operators and Others

Multiple Selection Using cond

(define atom?
  (lambda (x)
	  (cond
		  ((null? x) #f)
		  ((pair? x) #f)
		  (else #t))))
(define atom?
  (lambda (x)
	  (cond
		  ((null? x) #f)
		  ((pair? x) #f)
		  (#t #t))))

Lab - Tail Recursive Factorial


Tail Recursion(꼬리 재귀)

int fact(int n) {
	if(n == 0) return 1;
	else return n*fact(n-1);
}
int ifact(int n, int x = 1) {
	if(n == 0) return x;
	else return ifact(n-1, n*x);
}

Scheme을 사용한 factorial Tail recursive implementation

(define ifact
  (lambda (n x)
	  (if (= n 0) x
	  (ifact (- n 1) (* n x)))))

실행 결과

ifact