2015年6月16日火曜日

開発環境

Land of Lisp (M.D. Conrad Barski (著)、川合 史朗 (翻訳)、オライリージャパン)の4章(条件と判断)、4.3(ちょっとした条件式のテクニック)をSchemeで取り組んでみる。

4.3(ちょっとした条件式のテクニック)

コード(Emacs)

(begin 
  (define print (lambda (x) (display x) (newline)))
  (newline)
  
  (define odd?
    (lambda (n)
      (if (= (remainder n 2) 1)
          #t
          #f)))
  
  (print (and (odd? 5) (odd? 7) (odd? 9)))
  (print (or (odd? 4) (odd? 7) (odd? 8)))

  (define *is-it-even* #f)

  (print (or (odd? 4)
             (set! *is-it-even* #t)))
  (print *is-it-even*)

  (define *is-it-even* #f)
  (print (or (odd? 5)
             (set! *is-it-even* #t)))
  (print *is-it-even*)
  
  (define equal?
    (lambda (a b)
      (if (and (pair? a) (pair? b))
          (and (eq? (car a) (car b))
               (equal? (cdr a) (cdr b)))
          (eq? a b))))
  (define member
    (lambda (x items)
      (cond ((null? items) #f)
            ((equal? x (car items)) items)
            (else (member x (cdr items))))))
  (print (if (member 1 (quote (3 4 1 5)))
             (quote one-is-in-the-list)
             (quote one-is-not-in-the-list)))
  (print (member 1 (quote (3 4 1 5))))

  (print (if (member #f (quote (3 4 #f 5)))
             (quote false-is-in-the-list)
             (quote false-is-not-in-the-list)))

  (define find-if
    (lambda (pred-proc items)
      (cond ((null? items) #f)
            ((pred-proc (car items))
             (car items))
            (else (find-if pred-proc (cdr items))))))
  (print (find-if odd? (quote (2 4 5 6))))
  (print (if (find-if odd? (quote (2 4 5 6)))
             (quote there-is-an-odd-number)
             (quote there-is-no-odd-number)))
  (define false? (lambda (x) (eq? x #f)))
  (print (find-if false? (list 2 4 #f 6)))
  
  (quote done))

入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))

$ kscheme < sample3.scm
kscm> 
#t
#t
#<undefined>
#t
#t
#f
one-is-in-the-list
(1 5)
false-is-not-in-the-list
5
there-is-an-odd-number
#f
done
kscm> $

0 コメント:

コメントを投稿