[2021 Spring] CS61A 学习笔记 Homework 6: Scheme

hw06: https://inst.eecs.berkeley.edu/~cs61a/sp21/hw/hw06/#scheme-editor

CS 61A Scheme Specification: https://inst.eecs.berkeley.edu/~cs61a/sp21/articles/scheme-spec/

Scheme Built-In Procedure Reference: https://inst.eecs.berkeley.edu/~cs61a/sp21/articles/scheme-builtins/

Q2: Thane of Cadr

返回列表的第2、3个元素,参考题中给出的cddr即可。

(define (cddr s)
  (cdr (cdr s)))

(define (cadr s)
  'YOUR-CODE-HERE
)

(define (caddr s)
  'YOUR-CODE-HERE
)
(define (cddr s) (cdr (cdr s)))

(define (cadr s) (car (cdr s)))

(define (caddr s) (car (cdr (cdr s))))

Q3: Sign

用cond进行条件判断。

(define (sign val) 
    (cond 
        ((< val 0) -1)
        ((= val 0) 0)
        (else 1)))

Q4: Pow

用cond和even? 进行幂的运算,可以先写python版,再按照scheme语法来写。

(define (square x) (* x x))

(define (pow base exp) 
    (cond 
        ((= base 1) 1)
        ((= exp 0) 1)
        ((even? exp) (square (pow base (/ exp 2))))
        (else (* base (square (pow base (/ (- exp 1) 2)))))))

python版:

def squares(x): return x * x 

def pows(base, exp):
    if base == 1: return 1
    if exp == 0: return 1
    if exp % 2 == 0:
        return squares(pows(base, exp // 2))
    else:
        return base * squares(pow(base, exp // 2))
posted @ 2021-07-21 09:21  ikventure  阅读(1130)  评论(0编辑  收藏  举报