Q2: Over or Under
Define a procedure
over-or-underwhich takes in a numbernum1and a numbernum2and returns the following:
- -1 if
num1is less thannum2- 0 if
num1is equal tonum2- 1 if
num1is greater thannum2Challenge: Implement this in 2 different ways using
ifandcond!(define (over-or-under num1 num2) 'YOUR-CODE-HERE )
代碼其實本身不難, 主要是適應 scheme 語言的寫法, 條件分支有兩種寫法:
(if <predicate> <consequent> <alternative>)(cond (<condition> <consequent>) ...)
(define (over-or-under num1 num2)
(if (< num1 num2)
(print -1))
(if (= num1 num2)
(print 0))
(if (> num1 num2)
(print 1))
)
(define (over-or-under num1 num2)
(cond ( (< num1 num2) (print -1) )
( (= num1 num2) (print 0) )
( (> num1 num2) (print 1) ))
)
Q3: Make Adder
Write the procedure
make-adderwhich takes in an initial number,num, and then returns a procedure. This returned procedure takes in a numberincand returns the result ofnum + inc.Hint: To return a procedure, you can either return a
lambdaexpression ordefineanother nested procedure. Remember that Scheme will automatically return the last clause in your procedure.You can find documentation on the syntax of
lambdaexpressions in the 61A scheme specification!
實現高階函數的功能, 依舊是鍛煉 scheme 語言的掌握程度的. 題目都是之前課上講過的. 這里我用匿名函數來實現
(define (make-adder num)
(lambda (inc) (+ num inc))
)
Q4: Compose
Write the procedure
composed, which takes in proceduresfandgand outputs a new procedure. This new procedure takes in a numberxand outputs the result of callingfongofx.
用 scheme 語言實現符合數學中的復合函數, 也就是高階函數. 這里同樣可以用 lambda 函數
(define (composed f g)
(lambda (x) (f (g x) ) )
)
Q5: Make a List
In this problem you will create the list with the following box-and-pointer diagram:
Challenge: try to create this list in multiple ways, and using multiple list constructors!要求
題目要求我們按照給定的鏈表結構來生成對應的鏈表. 主要考察的是對 scheme 語言中 list 的掌握. 可以有多種實現方式
cons的方式, 這個方式很容易眼花, 最好是寫完之后在這里 驗證一下. 這里我真的寫得頭有點暈 😢list的方式, 這個代碼會比較短, 注意我們每次在調用(list ...)相當於在鏈表中多創建了一個方向
(define lst
(cons (cons 1 nil)
(cons 2 (cons (cons 3 (cons 4 nil))
(cons 5 nil))))
)
(define lst
(list (list 1)
2 (list 3 4)
5)
)
Q6: Remove
Implement a procedure
removethat takes in a list and returns a new list with all instances ofitemremoved fromlst. You may assume the list will only consist of numbers and will not have nested lists.Hint: You might find the built-in
filterprocedure useful (though it is definitely possible to complete this question without it).You can find information about how to use
filterin the 61A Scheme builtin specification!
這一題就是要我們在 scheme 的列表中移除掉值等於 item 的元素然后返回新的這個列表. 其實 scheme 的列表也就是鏈表. 所以這一題等效於我們要在鏈表中移除指定值的元素. 顯然, 這可以用遞歸來解決! 而且這一道題說沒有嵌套列表的情況存在, 這一道題就更簡單了 !
顯然 base case 就是鏈表為空的情況, 我們直接返回空. 否則:
- 當前節點的值 =
item, 我們刪除它, 遞歸處理子鏈表 - 當前節點的值 !=
item, 我們保留它, 遞歸處理子鏈表
(define (remove item lst)
(cond ( (null? lst) '() ) ; base case
( (= item (car lst)) (remove item (cdr lst))) ; exclude item
( else (cons (car lst) (remove item (cdr lst))))) ; include item
)

