scheme吧 关注:1,488贴子:962
  • 3回复贴,共1

几道题目求助

只看楼主收藏回复

1.Write the function filter that take a predicate and a list as its inputs and returns a list containing those elements that were satisfied by the predicate.
(filter odd? '(5 12 31 7 98 13) // returns (5 31 7 13)
(filter (lambda (x) (> x 10)) '(3 47 18 2 20) // returns (47 18 20)
(filter list? '(() 2 ((6) 4))) // returns (() ((6) 4))
2.Write the function reverse that takes a list as its input and returns a list with the order of those elements reversed.Note that any sublists are not reversed.
(reverse '(5 12 31 7 98 13)) // returns (13 98 7 31 12 5)
(reverse '((1 2) 3)) // returns (3 (1 2))
(reverse '(() 2 ((6) 4))) // returns (((6) 4) 2 ())
(reverse '()) // returns ()
3.Write the procedure safe-divider,which takes a numeric input that will be used as a numerator in a division expression.safe-divider returns a procedure that takes another numeric inputer that will be used as the denominator.When that procedure is called,if the denominator is zero,the word "cow" is returned(without the quotes).Otherwise,the numerator divided by the denomator is returned.
(define divide-by-12 (safe-divider 12))
(divide-by-12 4) // returns 3
(divide-by-12 -2) // returns -6
(divide-by-12 0) // returns 'cow
(define divide-by-20 (safe-divider 20))
(divide-by-20 0) // returns 'cow
(divide-by-20 4) // returns 5


1楼2017-09-17 21:02回复
    自己找找


    IP属地:上海3楼2017-11-28 19:30
    回复
      1.
      (define filter
      (lambda (f a)
      (if (null? a)
      '()
      ((lambda (b h t) (if b (cons h t) t))
      (f (car a))
      (car a)
      (filter f (cdr a))))))
      2.
      (define (reverse n)
      (define rev-it
      (lambda (x r)
      (if (null? x) r (rev-it (cdr x) (cons (car x) r)))
      )
      )
      (rev-it n '())
      )
      3.
      (define safe-divider
      (lambda (x)
      (lambda (y)
      (if (zero? y) 'cow (/ x y)))))


      IP属地:浙江4楼2019-01-20 21:52
      回复
        (define filter(lambda (proc ls)(cond((null? ls)'())((proc (car ls)) (cons (car ls) (filter proc (cdr ls))))(else (filter proc (cdr ls))))))
        (define reverse(lambda (ls)(cond ((null? ls) '()) (else (append (reverse (cdr ls)) (cons (car ls) '()))))))


        IP属地:福建5楼2019-05-17 17:21
        回复