Drkcore

17 11 2011 Scheme Tweet

継続を渡す(scheme修行14章)

leftmostの実装

(define atom?
  (lambda (x)
    (and (not (pair? x)) (not (null? x)))))

(define leftmost
  (letrec
      ((lm (lambda (l out)
         (cond
          ((null? l) (quote ()))
          ((atom? (car l))
           (out (car l)))
          (else
           (let ()
         (lm (car l) out)
         (lm (cdr l) out)))))))
    (lambda (l)
      (let/cc skip
    (lm l skip)))))

実行結果

gosh> (leftmost '((() (5 4) 1) 2 3))
5

面白い部分は次の継続を関数に渡しているところと

(let/cc skip (lm l skip)

let () で次々に関数を実行しているところ。

(let ()
  (lm (car l) out)
  (lm (cdr l) out))

アトムが見つかればその時点でそれ以降の計算はキャンセルされるので次々に実行する処理を書いていい。

ちょっと悟りが開けた。

この本面白いなぁ、何度が読みなおすことになりそう。

ProductName Scheme修行
Daniel P. Friedman and Matthias Felleisen
オーム社 / 2940円 ( 2011-06-15 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021