2015年6月12日金曜日

開発環境

Land of Lisp (M.D. Conrad Barski (著)、川合 史朗 (翻訳)、オライリージャパン)の4章(条件と判断)、4.2(条件分岐: If とその仲間たち)をSchemeで取り組んでみる。

4.2(条件分岐: If とその仲間たち)

コード(Emacs)

(begin 
  (define print (lambda (x) (display x) (newline)))
  (newline)
  
  (print (if (= (+ 1 2) 3)
             (quote yup)
             (quote nope)))

  (print (if (= (+ 1 2) 4)
             (quote yup)
             (quote nope)))

  (print (if (quote (1))
             (quote the-list-has-stuff-in-it)
             (quote the-list-is-empty)))

  (print (if (null? (quote (1)))
             (quote the-list-has-stuff-in-it)
             (quote the-list-is-empty)))

  (define odd?
    (lambda (n)
      (if (= (remainder n 2) 1)
          #t
          #f)))

  (print (if (odd? 5)
             (quote odd-number)
             (quote even-number)))

  (print (if (odd? 5)
             (quote odd-number)
             (/ 1 0)))

  ;; Scheme にも when と unless はあるけど、まだ kscheme に実装してない。。
  (define *number-is-odd* #f)
  (print (if (odd? 5)
             (begin (set! *number-is-odd* #t)
                    (quote odd-number))))
  (print *number-is-odd*)

  (print (if (not (odd? 4))
             (begin (set! *number-is-odd* #f)
                    (quote even-number))))

  (print *number-is-odd*)

  (define *arch-enemy* #f)
  ;; else を使うのが Common Lisp と少し違う
  (define pudding-eater
    (lambda (person)
      (cond ((eq? person (quote henrry))
             (set! *arch-enemy* (quote stupid-lisp-alien))
             (quote (curse you lisp alien - you ate my pudding)))
            ((eq? person (quote johnny))
             (set! *arch-enemy* (quote useless-old-johnny))
             (quote (i hope you choked on my pudding johnny)))
            (else (quote (why you eat my pudding stranger ?))))))
  (print (pudding-eater (quote johnny)))
  (print *arch-enemy*)
  (print (pudding-eater (quote george-cloony)))

  ;; Scheme にも case はあるけど、まだ kscheme に実装してない。。
  
  (quote done))

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

$ kscheme < sample2.scm
kscm> 
yup
nope
the-list-has-stuff-in-it
the-list-is-empty
odd-number
odd-number
odd-number
#t
even-number
#f
(i hope you choked on my pudding johnny)
useless-old-johnny
(why you eat my pudding stranger ?)
done
kscm> $

0 コメント:

コメントを投稿