Skip to content

Instantly share code, notes, and snippets.

View yao2030's full-sized avatar

yao2030 yao2030

  • Shanghai, China
View GitHub Profile
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
(define fold-right accumulate)
(define (reverse seq)
(define (last-pair list1)
(if (= (length list1) 1)
(car list1)
(last-pair (cdr list1))))
(define (but-last list1)
(if (= (length list1) 1)
'()
(cons (car list1) (but-last (cdr list1)))))
(define (reverse x)
(if (null? x)
;;
(define (accumulate op init seq)
(if (null? seq)
init
(op (car seq)
(accumulate op init (cdr seq)))))
;;
(define (accumulate-n op init seqs)
(if (null? (car seqs))
'()
(define (map p sequence)
(accumulate (lambda (x y) (cons (p x) y)) '() sequence))
(define (append seq1 seq2)
(accumulate cons seq2 seq1))
;; it took me about half an hour to figure length out.
(define (length sequence)
(accumulate (lambda (x y) (+ 1 y)) 0 sequence))
(define (subsets s)
(if (null? s)
(list '())
(let ((rest (subsets (cdr s))))
(append rest (map (lambda (x) (cons (car s) x)) rest)))))
(define (tree-map proc tree)
(cond ((null? tree) '())
((not (pair? tree)) (proc tree))
(else (cons (tree-map proc (car tree))
(tree-map proc (cdr tree))))))
(define (filter predicate sequence)
(cond ((null? sequence) '())
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(define (make-mobile left right)
(list left right))
(define (make-branch length structure)
(list length structure))
(define (left-branch x)
(car x))
(define (right-branch x)
(cadr x))
(define (branch-length x)
(car x))
(define (fringe x)
(cond ((null? x) x)
((not (pair? x)) (list x))
(list (append (fringe (car x)) (fringe (cdr x))))))
(define (last-pair list1)
(if (= (length list1) 1)
(car list1)
(last-pair (cdr list1))))
(define (but-last list1)
(if (= (length list1) 1)
'()
(cons (car list1) (but-last (cdr list1)))))
(define (reverse x)
(if (null? x)