Created
February 18, 2012 14:57
-
-
Save syou6162/1859652 to your computer and use it in GitHub Desktop.
Clojureでの継続の簡単な例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; プログラミングGaucheの継続の例をClojureで書いてみる | |
;; 継続がそもそもどういう概念なのか理解できると...いいな | |
;; まずCall-Return方式 | |
(defn find-fold [pred? proc seed lis] | |
(cond (empty? lis) seed | |
(pred? (first lis)) (let [seed2 (proc (first lis) seed)] | |
(find-fold pred? proc seed2 (rest lis))) | |
:else (find-fold pred? proc seed (rest lis)))) | |
(find-fold odd? + 0 (range 11)) ; 25 | |
(defn process [elt seed] | |
(println "found: " elt) | |
(cons elt seed)) | |
(find-fold odd? process '() (range 11)) | |
;; found: 1 | |
;; found: 3 | |
;; found: 5 | |
;; found: 7 | |
;; found: 9 | |
;; (9 7 5 3 1) | |
;; 次に継続渡し方式 | |
(defn find-fold2 [pred? proc-cont seed lis] | |
(cond (empty? lis) seed | |
(pred? (first lis)) | |
(proc-cont (first lis) | |
seed | |
(fn [seed2] (find-fold2 pred? proc-cont seed2 (rest lis)))) | |
:else (find-fold2 pred? proc-cont seed (rest lis)))) | |
(defn process-cont [elt seed cont] | |
(println "found: " elt) | |
(cont (cons elt seed))) | |
(find-fold2 odd? process-cont '() (range 11)) | |
;; found: 1 | |
;; found: 3 | |
;; found: 5 | |
;; found: 7 | |
;; found: 9 | |
;; (9 7 5 3 1) | |
(def next (atom nil)) | |
(defn break [val] val) | |
(defn process-break [elt seed cont] | |
(reset! next | |
#(do | |
(println "found: " elt) | |
(cont (cons elt seed)))) | |
(break nil)) | |
(find-fold2 odd? process-break '() (range 11)) ; nil | |
((deref next)) | |
; found: 1 | |
; nil | |
((deref next)) | |
; found: 3 | |
; nil | |
((deref next)) | |
; found: 5 | |
; nil | |
((deref next)) | |
; found: 7 | |
; nil | |
((deref next)) | |
; found: 9 | |
; (9 7 5 3 1) | |
((deref next)) | |
; found: 9 | |
; (9 7 5 3 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment