目录
List
;;基本定义方法
(define concert (cons "Da"
(cons "xiao"
empty)))
Extract the value from the list
Contract 的写法
(listof Str)->Bool
(listof Num)->Bool
小模版
;; (listof-X-template lox) PURPOSE
;; Examples:
(check-expect (listof-X-template empty) ANSWER)
(check-expect (listof-X-template (cons X empty)) ANSWER)
;; listof-X-template: (listof X) -> Any
(define (listof-X-template lox)
(cond [(empty? lox) ...]
[(cons? lox) (... (first lox)
(listof-X-template (rest lox)))]))
;; Tests
Wrapper Function
排序
insertion sort
;; (sort lon) sorts the elements of lon in non-decreasing order
;; Example:
(check-expect (sort (cons 3 (cons 4 (cons 2 (cons 5 (cons 1 empty))))))
(cons 1 (cons 2 (cons 3 (cons 4 (cons 5 empty))))))
;; sort: (listof Num) -> (listof Num)
(define (sort lon)
(cond [(empty? lon) empty]
[else (insert (first lon) (sort (rest lon)))]))
;; (insert n slon) inserts the number n into the sorted list slon
;; so that the resulting list is also sorted.
;; Example:
(check-expect (insert 3 (cons 1 (cons 4 (cons 5 empty))))
(cons 1 (cons 3 (cons 4 (cons 5 empty)))))
;; insert: Num (listof Num) -> (listof Num)
;; requires: slon is sorted in non-decreasing order
(define (insert n slon)
(cond [(empty? slon) (cons n empty)]
[(<= n (first slon)) (cons n slon)]
[else (cons (first slon) (insert n (rest slon)))]))
list 新写法
lists of lists
(define lst (cons (cons 1 (cons 2 empty))
(cons (cons 3 (cons 4 empty))
empty))
//consider list a value
// which appears in a big list as an element.
how to definition?
template
注:name and amount 是helper function
payroll represents (listof (list Str Num))
Dictionary
template
note: AL represents to (listof (list Nat Str))
look-up the value in AL
2D data
note: (cols-to 0 r nc) 用来造出来(listof Num)
一个函数处理两个list
case 1
只需判断一个list,另一个尾随
(cons (list 1 2) (list 3 4))->(list (list 1 2) 3 4)
(list (list 1 2) (list 3 4))->(list (list 1 2) (list 3 4))
(append (list 1 2) (list 3 4))->(list 1 2 3 4)
case 2
Two lists are in the same length.
case3
process at different rates
We need to consider about 4 possible end conditions.
ex. merge two ascending lists to a whole list which is also ascending.
强化版:
(define (merge lon1 lon2)
(cond [(empty? lon1) lon2] ; first two cases
[(empty? lon2) lon1] ; third case
[(< (first lon1) (first lon2))
(cons (first lon1) (merge (rest lon1) lon2))]
[else (cons (first lon2) (merge lon1 (rest lon2)))]))