練習メニューをschemeでもやってみよう。

今回は"サイコロの目がすべてでるまでサイコロを振る"

(use srfi-27)
(random-source-randomize! default-random-source)

(define (dice-roll)
  (define (roll state history count)
    (let ((n (+ 1 (random-integer 6))))
      (print n)
      (print "state: " state)
      (if (= (length state) 6)
          (list "count: " count "state: " state "history =>" history)
          (if (find (lambda (x) (= n x)) state)
              (roll state
                    (append history (list n))
                    (+ count 1))
              (roll (append state (list n))
                    (append history (list n))
                    (+ count 1))))))
  (roll '() '() 0))
(dice-roll)
;; gosh> dice-roll
;; gosh> 3
;; state: ()
;; 1
;; state: (3)
;; 6
;; state: (3 1)
;; 5
;; state: (3 1 6)
;; 2
;; state: (3 1 6 5)
;; 1
;; state: (3 1 6 5 2)
;; 3
;; state: (3 1 6 5 2)
;; 4
;; state: (3 1 6 5 2)
;; 4
;; state: (3 1 6 5 2 4)
;; ("count: " 8 "state: " (3 1 6 5 2 4) "history =>" (3 1 6 5 2 1 3 4))

自分で書いてみて分かったこと

schemeはあれこれ手を加えやすいような気がする。

  • printなどを加えてもあまり見た目が悪くならない
  • 処理の途中で変数に代入しなくてもコードが横に長くなることが抑えられる。
  • (その他上手く言語化できないけどrubyとはまた違った書きやすさ)

関数を調べるのに、

inforとaproposが便利。

(info 'info)