lazy-seq in Clojure (翻訳)

user> (def fib-seq
(lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))

;; => #'user/fib-seq
user> (def fib-seq (concat (lazy-seq [0 1]) (lazy-seq (map + (rest fib-seq) fib-seq))))
;; => #'user/fib-seq
user> (doall (take 2000 fib-seq))

内部のしくみ:

例に戻る:

user> (def fib-seq-temp [0 1 1 2 3])
user> (map + (rest fib-seq-temp) fib-seq-temp)
;; => (1 2 3 5)
user> (map + (rest [0 1]) [0])
;; => (1)
user> (map + (rest [0 1]) [1])
;; => (2)
user> (def fib-seq
(lazy-cat [0 1]
(map
(fn [a b]
(println (format "%d + %d" a b)
(+ a b))
(rest fib-seq) fib-seq)))
;; => #'user/fib-seq
user> (doall (take 10 fib-seq))
1 + 0
1 + 1
2 + 1
3 + 2
5 + 3
8 + 5
13 + 8
21 + 13
;; => (0 1 1 2 3 5 8 13 21 34)

lazy-seq マクロ

シーケンスの先頭を保持する

user> (defn infinite[] (lazy-seq (cons (rand) (infinite))))
;; => #'user/infinite
--user> (defn infinite-1[] (lazy-seq (cons (rand) (infinite-1))))
;; => #'user/infinite-1
user> (def zyx (infinite-1))

lazy-seq の重要点

参考:

--

--

--

Software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Takanori Ishibashi

Takanori Ishibashi

Software engineer

More from Medium

Pass By Value vs Reference! What’s the default really?

Solving a few functional programming exercises using Elixir

Dotfiles & Friends

Eight Queens Puzzle in TypeScript’s Type System

A chess piece with a golden crown on its top