(求救) 電腦程式語言 (Scheme) 有人會嗎??
有三題考古題裡面 發現不會做的問題
第一:
;; TYPE: list<X> -> list<pair<X, integer>>
;; EFFECTS: => the list of pairs of the form (cons x xc)
;; where x is an element of xs and xc is its frequency.
;; The result does not contain repeated elements - i.e.
;; each element of xs is processed once.
例: (freq-all ’(7 8 9 7 8 7))
=> ((7 . 3) (8 . 2) (9 . 1))
我的答案:
(define (num-in-list x xs)
(length (filter (lambda (n) (eq? x n)) xs)))
(define (list-without xs x)
(filter (lambda (y) (not (eq? x y))) xs))
(define (freq-first xs)
(let ((x (car xs)))
(cons (cons x (num-in-list x xs))
(list-without xs x))))
(define (freq-all xs)
(if (null? xs) null
(cons (freq-first xs)
(freq-all (cdr xs)))))
可是答案不對 我的程式出來是 ((7 . 3) (8 . 2) (9 . 1) (8.1) (7.1))
第一:
;; TYPE: list<X> -> list<pair<X, integer>>
;; EFFECTS: => the list of pairs of the form (cons x xc)
;; where x is an element of xs and xc is its frequency.
;; The result does not contain repeated elements - i.e.
;; each element of xs is processed once.
例: (freq-all ’(7 8 9 7 8 7))
=> ((7 . 3) (8 . 2) (9 . 1))
我的答案:
(define (num-in-list x xs)
(length (filter (lambda (n) (eq? x n)) xs)))
(define (list-without xs x)
(filter (lambda (y) (not (eq? x y))) xs))
(define (freq-first xs)
(let ((x (car xs)))
(cons (cons x (num-in-list x xs))
(list-without xs x))))
(define (freq-all xs)
(if (null? xs) null
(cons (freq-first xs)
(freq-all (cdr xs)))))
可是答案不對 我的程式出來是 ((7 . 3) (8 . 2) (9 . 1) (8.1) (7.1))