grylix
Programming Clojure, Fourth Edition: lazy streams (p. 104)
On Page 104 you describe several ways to define lazy streams in general or the stream of the fibonacci numbers in general.
I propose to demonstrate the definition of streams as the fixed point of a given function which maps a stream to another stream. The given function must be a productive function, i.e. a function,
that can generate at least the beginning of a sequence.
(defn fixedpoint [f]
(letfn
[(stream [ ] (lazy-seq (f (stream))))]
(stream))
)
Let’s define some examples, e.g. the stream of zeros, ones, or the stream of alternating zero and ones:
(set! *print-length* 20)
(def zeros (fixedpoint (fn [s] (cons 0 s))))
(def ones (fixedpoint (fn [s] (cons 1 s))))
(def zeroone (fixedpoint (fn [s] (cons 0 (cons 1 s)))))
but more interesting is the definition of the stream of integers
(def ints (fixedpoint (fn [s] (cons 0 (map inc s)))))
and the stream of fibonacci numbers
(def fibs (fixedpoint (fn [s] (cons 0 (map + s (cons 1 s))))))
For me, this definition is very simple and clear.
Best wishes
Dominik
Popular Pragmatic Bookshelf topics
Other popular topics
Categories:
Sub Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /python
- /js
- /rails
- /security
- /go
- /swift
- /vim
- /clojure
- /java
- /emacs
- /haskell
- /svelte
- /typescript
- /onivim
- /kotlin
- /c-plus-plus
- /crystal
- /tailwind
- /react
- /gleam
- /ocaml
- /flutter
- /elm
- /vscode
- /ash
- /html
- /opensuse
- /zig
- /centos
- /deepseek
- /php
- /scala
- /react-native
- /lisp
- /sublime-text
- /textmate
- /nixos
- /debian
- /agda
- /deno
- /django
- /kubuntu
- /arch-linux
- /nodejs
- /spring
- /revery
- /ubuntu
- /manjaro
- /diversity
- /lua
- /julia
- /markdown
- /slackware









