2019-03-10

; 变量定义
(define pi (* 4 (atan 1 .0)))

; 方法定义
(define (sum-gp a0 r n)
 (* a0
  (if (= r 1)
   n
   (/ (- 1 (expt r n)) (- 1 r)))))

; if用法
(define (abs n)
 (if (< n 0)
  (- 0 n)
  n))

; cond条件用法
(define (trans grade)
 (cond
  ((>= grade 80) "A")
  ((<= 60 grade 79) "B")
  ((<= 40 grade 59) "C")
  (else "D")))

; 递归阶乘
(define (fact n)
 (if (= n 1)
  1
  (* n (fact (- n 1)))))

; 递归表中所有元素翻倍
(define (list*2 ls)
 (if (null? ls)
  '()
  (cons (* 2 (car ls))
   (list*2 (cdr ls)))))

; 递归统计列表长度
(define (my-length ls)
 (if (null? ls)
  0
  (+ (my-length (cdr ls)) 1)))

;递归求表元素之和
(define (list-sum ls)
 (if (null? ls)
  0
  (+ (list-sum (cdr ls)) (car ls))))

; 递归删除指定元素
(define (list-remove ls x)
 (if (null? ls)
  '()
  (if (eqv? (car ls) x)
   (list-remove (cdr ls) x)
   (cons (car ls) (list-remove (cdr ls) x)))))

; 递归获取元素在列表中第一次出现的位置
(define (position x ls)
 (position-aux x ls 0))

(define (position-aux x ls i)
 (cond
  ((null? ls) #f)
  ((eqv? x (car ls)) i)
  (else (position-aux x (cdr ls) (+ i 1)))))


; 尾递归反转列表
(define (list-revert ls)
 (letrec ((iter (lambda (ls0 ls1)
                 (if (null? ls0)
                  ls1
                  (iter (cdr ls0) (cons (car ls0) ls1))))))
  (iter ls ())))

; 尾递归求数值列表和
(define (list-sum-tail ls)
 (letrec ((iter (lambda (ls0 n)
                 (if (null? ls0)
                  n
                  (iter (cdr ls0) (+ (car ls0) n))))))
  (iter ls 0)))

; 尾递归计算阶乘
(define (fact-tail n)
 (fact-rec n n))

(define (fact-rec n p)
 (if (= n 1)
  p
  (let ((m (- n 1)))
   (fact-rec m (* p m)))))

你可能感兴趣的:(2019-03-10)