The gtwiwtg Reference Manual

Table of Contents

Next: , Previous: , Up: (dir)   [Contents][Index]

The gtwiwtg Reference Manual

This is the gtwiwtg Reference Manual, version 0.1.1, generated automatically by Declt version 3.0 "Montgomery Scott" on Tue Dec 22 13:39:44 2020 GMT+0.


Next: , Previous: , Up: Top   [Contents][Index]

1 Introduction

GTWIWTG

Generators The Way I Want Them Generated

(Technically not generators, but iterators.)

The GTWIWTG library is meant to be small, explorable, and understandable. The source code is meant to be legible and straightforward.

Every symbol exported from the GTWIWTG package has a useful docstring. Many docstrings include examples of use.

Table Of Contents

Installation

git clone https://github.com/cbeo/gtwiwtg /path/to/quicklisp/local-projects/

(ql:quickload :gtwiwtg)
(use-package :gtwiwtg)

First, Some Action

Here are a few examples to show you what you can do. A more involved example apears at the end of the document, following the tutorial.

All The Primes


> (defun prime-p (n)
    "Naive test for primes."
    (loop
       :for x :from 2 :upto (sqrt n)
       :when (zerop (mod n x)) :do (return nil)
       :finally (return t)))

> (defun all-primes ()
    "Creates a generator that produces an infinite series of primes."
     (filter! #'prime-p (range :from 2)))

> (take 10 (all-primes)) ;; (2 3 5 7 11 13 17 19 23 29)

Fun With Fibonacci


> (defun fibs ()
    "Creates an infinite series of Fibonacci numbers."
    (from-recurrence
     (lambda (n-1 n-2) (+ n-1 n-2))
     1 0))

;; First ten Fibonacci numbers
> (take 10 (fibs)) ;; (1 2 3 5 8 13 21 34 55 89) 

;; Just the 40th Fibonacci number, indexed from 0
> (car (pick-out '(40) (fibs))) ;; 267914296

A Kind Of Grep


> (defun grepper (pattern file)
   (filter! (lambda (idx-line) (search pattern (second idx-line)))
            (zip! (range) (file-lines file))))


> (for (idx line) (grepper "defun" "examples.lisp")
     (format t "~4a: ~a~%" idx line))


12  : (defun prime-p (n)
19  : (defun all-primes ()
37  : (defun fibs ()
52  : (defun fill-and-insert (idx elem vec buffer)
69  : (defun thread-through (elem vec)
86  : (defun perms (vec)
104 : ;; (defun perms (vec)
115 : (defun grepper (pattern file)

Tutorial

GTWIWTG is a tiny library for creating and using generators.

If you have never heard of generators before, let me offer a definition, but not the definition.

For the purposes of this library, a generator is an object that can produce a series of values, one value at a time. Generators are sometimes convenient when you want to deal with series that are too long to fit into memory. They also help when you want to generate sequential data using recurrence relations, as in the Fibonacci example above.

Three Kinds Of Function

In GTWIWTG, there are three kinds of functions.

  1. functions that construct generators
  2. functions that combine generators
  3. functions and macros that consume generators.

The Breadwinning Constructors

The two most common generator constructors are:

Here are some examples using range and seq to make generators.


  ;; all positive integers starting at 0
> (range)

#<GTWIWTG::GENERATOR! {1001A7DF63}>

 ;; positive integers from 0 to 9
> (range :to 10)

#<GTWIWTG::GENERATOR! {1001A90CA3}> 

;; positive integers from 0 to 10 
> (range :to 10 :inclusive t) 

#<GTWIWTG::GENERATOR! {1001A90CA3}> 

;; numbers between 4.0 and -15.7 incremented by -0.44
> (range :from 4 :to -15.7 :by -0.44) 

#<GTWIWTG::GENERATOR! {1001B09D63}>

;; the characters in the string "hello"
> (seq "hello")

#<GTWIWTG::GENERATOR! {1001B93E63}>

;; the symbols in the list
> (seq '(h e l l o))

#<GTWIWTG::GENERATOR! {1001BAB273}>

;; the symbols in the vector 
> (seq #('h 'e 'l 'l 'o))

#<GTWIWTG::GENERATOR! {1001BE4883}>

As you can see, generators are objects. Nothing is generated until you consume a generator. As a quick, but greatly impoverished, example, consider this:


;; get the first 4 numbers from the range starting at 20
> (take 4 (range :from 20))

(20 21 22 23)

Other Constructors

Here is a brief listing of the other generator constructors in GTWIWTG:

You can see some of these in action in the examples section at the top of this document.

The Combination and Transformation Functions

You can create more intersting and more specific generators by using a few higher-order functions to combine and transform simple generators.

These transformations are desirable because they can be performed before any elements are produced.

That is, if you think of a generator as a computation that produces a series of values, then transformation functions allow you to incrementally "build up" a desired computation before it is run.

The three core transformation functions are:

Admittedly, the behavior of inflate! is difficult to grok by reading a description. Once you begin to use it, however, it becomes indispensible.

[NB: inflate! is really a kind of monadic bind operator in disguise.]

Here are some simple examples of their use:


;; map cons over two generators
> (map! #'cons (times 3) 
               (range :from 8))

#<GTWIWTG::GENERATOR! {1001CB28D3}>

;; consuming the above using collect
> (collect (map! #'cons (times 3) (range :from 8)))

((0 . 8) (1 . 9) (2 . 10))

;; Notice that map! stops generating after 3 steps even though 
;; (range :from 8) is an infinite generator. This is because (times 3)
;; only generates 3 values.

;; get just the even values from a generator: 
> (collect (filter! #'evenp (times 10)))

(0 2 4 6 8)

;; generate (times N) for each N in the range 1 to 4
> (for x (inflate! #'times (range :from 1 :to 4 :inclusive t))
    (when (zerop x) (terpri))
    (princ x) (princ #\Space))

0         ; (times 1)
0 1       ; (times 2)
0 1 2     ; (times 3)
0 1 2 3   ; (times 4)

The Other Combinations and Transformations

A Word Of Warning!

(Or, there's a reason those forms all end in !.)

You must be cautious when incrementally building up generators. The reason for caution is that generators cannot be "combined twice". If you are storing intermediate generators in a let binding, for example, you may be tempted to pass those bound variables into generator combination functions more than once. If you do, an error will be signalled.

The general rule is: if you pass a generator to more than one combining function (those whose names end in !), or if you pass the same generator to one such function at two argument positions, then an error will be raised and new the generator will not be built.

Internally, the library keeps track of whether or not generators have been combined with others. Don't quote me on it, but I think that the library will prevent you from making generators with surprising (i.e. erroneous) behavior.

Here is an example to show you the illegal behavior:


> (let ((ten-times (times 10)))
    (zip! ten-times ten-times))

; Evaluation aborted on #<SIMPLE-ERROR "~@<The assertion ~S failed~:[.~:; ~
                                           with ~:*~{~S = ~S~^, ~}.~]~:@>" {10046A61D3}>.

The gist is that we tried to zip a generator with itself. Such behavior is not allowed.

An ongoing goal is to make those errors nicer to look at so that you can more easily pin-point where you goofed.

The Fundamental Consumer

Finally! Once you have built up your generators using constructors and combinations, you want to actually use them for something. This is where consumers come in.

There is one fundamental consumer, a macro, called for. (Triumphant Horns Play)

Every other consumer in GTWIWTG uses for under the hood.

Here is how it looks when you use it:


> (for x (times 3)
    (print x))

0 
1 
2 

> (for (x y) (zip! (seq "hello") (range))
    (format t "~a -- ~a~%" x y)
    (when (= 4 y) 
      (princ "world!")
      (terpri))

h -- 0
e -- 1
l -- 2
l -- 3
o -- 4
world!

> (let* ((ten-times (times 10))
         (doubled (map! (lambda (x) (* 2 x)) ten-times))
         (incremented (map! #'1+ doubled))
         (indexed (zip! (range) incremented)))
    (for (index number) indexed
      (princ index) 
      (princ " -- ") 
      (princ number) 
      (terpri)))

0 -- 1
1 -- 3
2 -- 5
3 -- 7
4 -- 9
5 -- 11
6 -- 13
7 -- 15
8 -- 17
9 -- 19

As you can see for has 3 basic parts: a binding form, a generator form, and a body.

The binding form is either a variable, like x above, or is a form suitable for use in the binding form of a DESTRUCTURING-BIND, like (x y) above.

On each iteration, the variables in the binding form are bound to successive values generated by the generator form. Notice that you do not need to inline your generator form, you can build it up and pass it in as in the third example above.

Finally, the body is evaluated for each iteration.

[Aside: for used to be called iter, but I didn't want to step on the toes of series and iterate users :P].

Generators are Consumed at Most Once

Even if you don't think you're "using up" the whole generator, a generator can only be passed to a single consumer. Once that consumer finishes, the generator is consumed. Here is an example:


>(let ((foo (seq "foobar")))
   (print (take 2 foo))
   (print (collect foo)))

(#\f #\o) 
NIL 

Even though you only seemed to use the first two members of the generator foo, the take form will mark the generator as having been consumed in its entirety.

That is, even when the whole sequence was not actually generated, a consuming form leaves its generator in an unusable state. This approach has been taken in order to automatically close streams for stream-backed generators - i.e. it has been done in the spirit of letting you not have to think about how generators work.

You need only remember the rule: Generators Are Consumed At Most Once.

The Accumulating Consumer

The next most common consuming form is fold, which lets you consume values produced by a generator while accumulating some data along the way.

Here is how you would do a classic summing operation:

> (fold (sum 0) (x (times 10)) 
        (+ sum x))
45

The syntax is (fold (acc init) (iter-var gen) update).

First, you declare and initialize an accumulator variable. In the above that is the form (sum 0), which declares a variable called sum initialized to 0.

Next comes your iteration variable and generator form. These have the same syntax as for. So in the above we bind a variable x to each successive value generated by (times 10).

Finally, you write a single update form whose value becomes bound to your accumulator variable. In the above example sum is set to (+ sum x).

The fold form returns the final value of the accumulator.

Here are some more folds:


;; some funky calculation 

> (fold (acc 0)
        ((x y) (zip! (times 10) (range :by -1)))
        (sqrt (+ acc (* x y))))
#C(0.444279 8.986663)

;; Example: building a data structure

> (fold (plist nil) 
        ((key val)
         (zip! (seq '(:name :occupation :hobbies))
               (seq '("buckaroo banzai" 
                      "rocker" 
                      ("neuroscience" "particle physics" "piloting fighter jets")))))
         (cons key (cons val plist)))

 (:HOBBIES ("neuroscience" "particle physics" "piloting fighter jets")
  :OCCUPATION "rocker" :NAME "buckaroo banzai")

The Remaining Consumers

All of the remaining consumers are regular functions that have been built using for and fold. They are:

The pick-out consumer is interesting enough to see a quick example of:

;; pick out characters and index 1 and index 4
> (pick-out '(1 4) (seq "generators"))
(#\e #\r)

;; you can do this in any order
> (pick-out '(4 1) (seq "generators"))
(#\r #\e)

;; you can even repeat indices
> (pick-out '(4 1 1 4 2) (seq "generators"))
(#\r #\e #\e #\r #\n)

Anaphoric Consumer Macros

If you would like to use for and fold macros with a little less visual noise (but sacrificing some of their flexibility), you can use the gtwiwtg.anaphora package. Here's an example:


> (use-package :gtwiwtg)          ;; gets you the core package
> (use-package :gtwiwtg.anaphora) ;; gets you the two extra anaphoric consumers

;; ordinary for
> (for x (times 3) (print x))

0 
1 
2 

;; anaphoric for
> (afor (times 3) (print it))    ;; the variable IT is provided by AFOR
0
1
2

;; ordinary fold
> (fold (sum 0) (x (times 10)) (+ sum x))
45

;; anaphoric fold
> (afold 0 (times 10) (+ acc it))  ;; variables IT and ACC are provided by AFOLD
45 

Making New Generators

Generators are subclasses of gtwiwtg::generator! that have at least two methods specialized on them:

Additionally, if your generator needs to perform cleanup after it is consumed, you can implement the :after method combination for the method

None of the above are meant to be called by users of the library, which is why they are not exported symbols. But if you want to make your own generators you can.

A silly example:


> (defclass countdown (gtwiwtg::generator!)
    ((value :accessor countdown-value 
            :initarg :value 
            :initform 0)))

> (defmethod gtwiwtg::next ((g countdown))
    (decf (countdown-value g)))
  
> (defmethod gtwiwtg::has-next-p ((g countdown))
    (plusp (countdown-value g)))
  
;; you might also want a constructor 

> (defun countdown (n) (make-instance 'countdown :value n))

;; now you can use it:

> (for x (countdown 4) (print x))
  
3 
2 
1 
0 

You can see that next ASSUMES that there is a next value. This is one of the reasons you are not ment to call next manually. The for consumer automatically checks that there is a next value before trying to get it.

The Naughty Consumer

Now that the mysteries that make generators go have been explained in the previous section, you may be tempted to manually call next and has-next-p on your generators. If you must do this, you should use the with-generator macro:


> (with-generator (gen (seq "a1b2c3"))
     (when (gtwiwtg::has-next-p gen)
       (princ (gtwiwtg::next gen))
       (terpri)))
a

The with-generator form will ensure that the generator is properly closed. It could be useful with generators backed by input streams that need a custom logic, or perhaps in some case where you need to interleave operations between multiple generators. I'm not sure if you ever will need it, but the library provides it just in case.

The Permutations Example

One final example to show you what you can do. Here is a function that generates all of the permutations of a sequence passed to it, one at a time. It is a good example of the usefulness of inflate!.


(defun perms (vec)
  "Creates a generator that produces all of the permutations of the
   vector VEC, one at a time."
  (if (= 1 (length vec)) (seq (list vec))
      (let ((elem (elt vec 0))
            (subperms (perms (make-array (1- (length vec))
                                         :displaced-to vec         ; share vec's memory
                                         :displaced-index-offset 1
                                         :element-type (array-element-type vec)))))
        (inflate! (lambda (subperm) (thread-through elem subperm)) 
                  subperms))))

The basic flow is:

  1. single out the first element of the vector
  2. make a generator for permutations of the remainder of the vector
  3. return a generator that "adds back" the singled out element at each possible spot in each permutation.

The interesting bit about this is that we recursively compute permutation generators for the subvectors of vec in a classic divide-and-conquer way, and then use inflate! to combine those "generated sub-generators" into a single generator, which we return.

The above code is made significantly noisier by the use of displaced arrays. Displaced arrays let us share memory with the original vector.

For each "sub permutation", we create a new generator using a generator constructor called thread-through. This is the part where we "add back" the singled out element.

(defun thread-through (elem vec)
  "Creates a generator that produces a series of N vectors of length
   N, where N is one greater than the length of VEC.  The vectors
   produced by this generator have the same contents as VEC but have ELEM
   inserted at each possible spot, N spots in all. 

   Note: The generator reuses the memory that it returns on each step. If
   you intend to collect the values of the generator, you should copy
   them on each iteration."
   
  (let ((buffer (concatenate 'vector vec (list elem)))) ;; reusable buffer
    (map! (lambda (idx)
            (fill-and-insert idx elem vec buffer)
            buffer)
          (range :from 0 :to (length vec) :inclusive t))))

And this function uses a utility function called fill-and-insert that just fills a buffer, which I pulled out into its own function for clarity:


(defun fill-and-insert (idx elem vec buffer)
  "A utilty function that modifies BUFFER. 

The length of BUFFER is assumed to be one greater than the length of
VEC.

This function fills the first IDX fields of BUFFER with the first IDX
fields of VEC. It fills the field of BUFFER at IDX with ELEM. And it fills
the remaining fields of BUFFER with the remaining fields of VEC.
"

  (loop :for i :below (length buffer)
     :when (= i idx) :do (setf (aref buffer idx) elem)
     :when (< i idx) :do (setf (aref buffer i)
                               (aref vec i))
     :when (> i idx) :do (setf (aref buffer i)
                               (aref vec (1- i))))  )

And here's a quick demo of its use:


;; the map! is to turn vectors back into strings for ease of viewing
(for perm (map! (lambda (x) (concatenate 'string x)) 
                (perms "abcd"))
  (print perm))

"abcd" 
"bacd" 
"bcad" 
"bcda" 
"acbd" 
"cabd" 
"cbad" 
"cbda" 
"acdb" 
"cadb" 
"cdab" 
"cdba" 
"abdc" 
"badc" 
"bdac" 
"bdca" 
"adbc" 
"dabc" 
"dbac" 
"dbca" 
"adcb" 
"dacb" 
"dcab" 
"dcba" 

We could have generated all 121645100408832000 permutations of "generators are cool", and, though it would have taken us an eternity (a little more than 1000 years on a single core of my machine), the memory consumption would stay at an even keel.


Next: , Previous: , Up: Top   [Contents][Index]

2 Systems

The main system appears first, followed by any subsystem dependency.


Previous: , Up: Systems   [Contents][Index]

2.1 gtwiwtg

Author

Colin Okay <okay@toyful.space>

License

GPLv3

Description

Lazy-ish iterators

Version

0.1.1

Source

gtwiwtg.asd (file)

Components

Next: , Previous: , Up: Top   [Contents][Index]

3 Files

Files are sorted by type and then listed depth-first from the systems components trees.


Previous: , Up: Files   [Contents][Index]

3.1 Lisp


Next: , Previous: , Up: Lisp files   [Contents][Index]

3.1.1 gtwiwtg.asd

Location

gtwiwtg.asd

Systems

gtwiwtg (system)


Next: , Previous: , Up: Lisp files   [Contents][Index]

3.1.2 gtwiwtg/package.lisp

Parent

gtwiwtg (system)

Location

package.lisp

Packages

Next: , Previous: , Up: Lisp files   [Contents][Index]

3.1.3 gtwiwtg/gtwiwtg.lisp

Dependency

package.lisp (file)

Parent

gtwiwtg (system)

Location

gtwiwtg.lisp

Exported Definitions
Internal Definitions

Previous: , Up: Lisp files   [Contents][Index]

3.1.4 gtwiwtg/anaphora.lisp

Dependency

gtwiwtg.lisp (file)

Parent

gtwiwtg (system)

Location

anaphora.lisp

Exported Definitions

Next: , Previous: , Up: Top   [Contents][Index]

4 Packages

Packages are listed by definition order.


Next: , Previous: , Up: Packages   [Contents][Index]

4.1 gtwiwtg.anaphora

Source

package.lisp (file)

Use List

common-lisp

Exported Definitions

Previous: , Up: Packages   [Contents][Index]

4.2 gtwiwtg

Source

package.lisp (file)

Use List

common-lisp

Exported Definitions
Internal Definitions

Next: , Previous: , Up: Top   [Contents][Index]

5 Definitions

Definitions are sorted by export status, category, package, and then by lexicographic order.


Next: , Previous: , Up: Definitions   [Contents][Index]

5.1 Exported definitions


Next: , Previous: , Up: Exported definitions   [Contents][Index]

5.1.1 Macros

Macro: afold INIT GENERATOR UPDATE

Anaphoric FOLD. Binds the values produced by GENERATOR to IT, and binds the accumulating variable to ACC.

Example:

> (afold 0 (times 10) (+ acc it))
45

Package

gtwiwtg.anaphora

Source

anaphora.lisp (file)

Macro: afor GENERATOR &body BODY

Anaphoric FOR. Binds the values produced by GENERATOR to the variable IT.

Example:

> (afor (times 3) (print it))
0
1
2

Package

gtwiwtg.anaphora

Source

anaphora.lisp (file)

Macro: fold (ACC INIT-VAL) (VAR-EXP GEN) EXPR

The accumulating generator consumer.

ACC is a symbol and INIT-VAL is any lisp expression. ACC is where
intermediate results are accmulated. INIT-VAL is evaluated to
initialize ACC.

VAR-EXP can be either a symbol, or a form suitable for using as the
binding form in DESTRUCTURING-BIND.

GEN is an expression that should evaluate to a generator.

EXPR is a sigle lisp expression the value of which becomes bound to
ACC on each iteration.

When iteration has concluded, ACC becomes the value of the FOLD form.

Example: standard summing

> (fold (sum 0) (x (times 10)) (+ sum x))

45

Example: a usless calculation

> (fold (acc 0)
((x y) (zip! (times 10) (range :by -1)))
(sqrt (+ acc (* x y))))

#C(0.444279 8.986663)

Example: building data

> (fold (plist nil)
((key val)
(zip! (seq ’(:name :occupation :hobbies))
(seq ’("buckaroo banzai"
"rocker"
("neuroscience" "particle physics" "piloting fighter jets"))))) (cons key (cons val plist)))

(:HOBBIES ("neuroscience" "particle physics" "piloting fighter jets") :OCCUPATION "rocker" :NAME "buckaroo banzai")

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Macro: for VAR-EXP GEN &body BODY

The basic generator consumer.

VAR-EXP can be either a symbol, or a form suitable for using as the binding form in a DESTRUCTURING-BIND.

GEN is an expression that should evaluate to a generator.

BODY is a list of any forms you like. These forms will be evaluated for each value produced by GEN.

FOR akes care of running any clean up that the generator requires. E.g. If the generator is backed by an open stream, the stream will be closed. E.g. If the generator was built using FROM-THUNK-UNTIL, then the CLEAN-UP thunk will be run before FOR exits.

Every other consumer is built on top of FOR, and hence, every other consumer will also perform clean up.

Example:

(for (x y) (zip! (repeater ’a ’b ’c) (times 5))
(format t "~a – ~a~%" x y))

A – 0
B – 1
A – 2
B – 3
A – 4

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Macro: with-generator (VAR GEN) &body BODY

Use this if you absolutely must manually call NEXT and HAS-NEXT-P. It will ensure that the generator bound to VAR will be stopped and cleaned up properly.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)


Previous: , Up: Exported definitions   [Contents][Index]

5.1.2 Functions

Function: argmax FN GEN

Consumes GEN. Returns a pair (X . VALUE) such that (FUNCALL FN X)
is maximal among the values of GEN. VALUE is the value of (FUNCALL FN X)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: argmin FN GEN

Consumes GEN. Returns a pair (X . VALUE) such that (FUNCALL FN X)
is minimal among the values of GEN. VALUE is the value of (FUNCALL FN X)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: average GEN

Consumes GEN, returning its average value.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: collect GEN

Consumes GEN by collecting its values into a list.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: concat! GEN &rest GENS

Returns a generator that is the concatenation of the generators
passed as arguments.

Error Conditions:
- If any of the generators compare EQL, an error will be signalled.
- If any of the generators has been used elsewhere, an error will be sigalled.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: file-bytes FILE

Creates a generator that produces the bytes of a file. The stream to the file is closed when the generator finishes.

FILE is a path to a file.

The last generated value of the returned generator will be NIL.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: file-chars FILE

Creates a generator that produces the characters of a file. The stream to the file is closed when the generator finishes.

FILE is a path to a file.

The last generated value of the returned generator will be NIL.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: file-lines FILE

Creates a generator that produces the lines of a file. See FROM-INPUT-STREAM for more details about stream-backed-generators.

FILE is a path to a file.

The last generated value of the returned generator will be NIL.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: filter! PRED GEN

Creats a generator that generates the values of GEN for which PRED is non null.

Error Condition:
- If GEN has been used elsewhere, an error will be signalled.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: from-input-stream STREAM STREAM-READER

Create a generator from a STREAM.

You must supply as STREAM-READER function that accepts the stream as its only argument and returns NIL when the stream has run out of data, Non-NIL otherwise.

The new generator will return NIL as its final generated value..

Consumers of the new generator (forms like FOR, FOLD, COLLECT, and so on) will ensure that the stream is properly closed - you don’t need to worry. If, however, you create a stream-backed-generator but do not actually consume it, then the stream will not be properly closed. Always consume your generators by passing them to a consumer!

Here is an example:

(take 2 (from-input-stream
(open "hey.txt")
(lambda (s) (read-char s nil nil))))

(#\h #\e)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: from-recurrence REC N-1 &rest N-M

Creates a generator from a recurrence relation.

REC is a function of M arguments.

The Nth value of the series generated by the new generator is the result of calling REC on the previoius M results.

N-1 and N-M are used to initialize the recurrence. (1+ (LENGTH N-M)) should be M, the number of arguments acepted by REC.

Example

> (let ((fibs (from-recurrence #’+ 1 0)))
(take 10 fibs))

(1 2 3 5 8 13 21 34 55 89)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: from-thunk THUNK

Creates a generator that produces an inifinte series of values that are the return value of (FUNCALL THUNK).

If you need to create a stopping condition on your thunk-backed generator, see FROM-THUNK-UNTIL.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: from-thunk-times THUNK TIMES

Creates a generator that produces its values by calling (FUNCALL THUNK) exactly TIMES times.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: from-thunk-until THUNK &key UNTIL CLEAN-UP

Creates a generator that produces a series of values by successively calling (FUNCALL THUNK). The iterator stops whenever (FUNCALL UNTIL) is non null.

If a CLEAN-UP thunk is supplied, it will be run after the consumption of the new generator has finished. (Consumers are forms like FOR, COLLECT, FOLD, and so on.)

By default, UNTIL is the function (CONSTANTLY NIL). I.e. it will generate forever.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: indexed! GEN

Is shorthand for (ZIP! (RANGE) GEN)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: inflate! FN GEN &key EXTRA-CLEANUP

FN is expected to be a function that accepts elements of GEN and
returns a new generator.

The generator (INFLATE! FN GEN) generates each element of an
intermediate generator (FN X) for each X generated by GEN.

When a thunk is supplied to EXTRA-CLEANUP, then that thunk will be
called when the inflated generator is stopped. EXTRA-CLEANUP exists
for the case when FN returns generators that are not being created
within the body of FN, but are merely being "looked up" somehow. See
the implementation of CONCAT! for an example.

Here is an example:

> (let ((keys (seq ’(:name :occupation :hobbies)))
(vals (seq ’("buckaroo banzai"
"rocker"
("neuroscience" "particle physics" "piloting fighter jets"))))) (collect (inflate! #’seq (zip! keys vals))))

(:NAME "buckaroo banzai"
:OCCUPATION "rocker"
:HOBBIES ("neuroscience" "particle physics" "piloting fighter jets"))

Error Conditions:
- If GEN has been used elsewhere, an error will be signalled.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: inject! FN GEN

Injects an effect into a generator. Use this to add a side-effect to the value generation process.

Under most circumstances, the new generator produces exactly the same values as GEN. If, however, the values generated by GEN are being looked up in some remote memory location, and if FN is mutating that memory, then the new generator may produce different values.

Possibly good for debugging.

Example:

> (map! #’reverse
(inject! #’print ; look at values before they’re reversed (zip! (range)
(repeater :cool :beans)
(seq "banzai!"))))

> (collect *)

(0 :COOL #b) ;these are printed to stdout
(1 :BEANS #a)
(2 :COOL #n)
(3 :BEANS #z)
(4 :COOL #a)
(5 :BEANS #i)

((#b :COOL 0) ; and this is what collect returns
(#a :BEANS 1)
(#n :COOL 2)
(#z :BEANS 3)
(#a :COOL 4)
(#i :BEANS 5))

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: intersperse! GEN1 GEN2 &rest GENS

Produces a generator that intersperses one value from each of its argument generators, one after the other, until any of those generators run out of values.

Examples:

> (intersperse! (seq ’(:name :job :hobbies))
(seq ’("buckaroo banzai" "rocker" ("neuroscience"
"particle physics"
"flying fighter jets"))))

> (collect *)

(:NAME "buckaroo banzai" :JOB "rocker" :HOBBIES ("neuroscience" "particle physics" "flying fighter jets"))

> (intersperse! (times 5) (repeater ’a ’b ’c) (range :by -10))

> (collect *)

(0 A 0 1 B -10 2 C -20 3 A -30 4 B -40)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: map! MAP-FN GEN &rest GENS

Maps a function over a number of generators, returning a generator
that produces values that result from calling MAP-FN on those
generators’ values, in sequence.

The resulting generator will stop producing values as soon as any one
of the source generators runs out of arguments to pass to
MAP-FN. I.e. The new generator is as long as the shortest argument.

Error Conditions:
- If any of the generators compare EQL an error will be signalled
- If any of the generators have been used elsewhere, an error will be signalled.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: maximum GEN

Consumes GEN, returning its maximum value.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: merge! COMPARATOR GEN1 GEN2 &rest GENS

Emulates the behavior of MERGE (in the ANSI standard), but for generators.

The emulation is not perfect, but it holds in the following sense: If
all the inputs are sorted according to COMPARATOR then the output will
also be sorted according to COMPARATOR.

The generator created through a merge has a length that is the sum of
the lengths of the arguments to MERGE!. Hence, if any of the arguments
is an infinite generator, then the new generator is also infinite.

An example:

> (collect (merge! #’<
(times 4)
(range :from 4 :to 10 :by 2)
(range :from -10 :to 28 :by 6)))

(-10 -4 0 1 2 2 3 4 6 8 8 14 20 26)

Error Conditions:
- If any of the generators compare EQL, an error will be signalled.
- If any of the generators have been used elsewhere, an error will be signalled.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: minimum GEN

Consumes GEN, returning its minimum value.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: noise &optional ARG

Creates a generator that produces an infinite series of random numbers that are the result of calling (RANDOM ARG).

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: pick-out INDEXES GEN

Consumes GEN by picking out certain members by their index.

INDEXES is a list of non-negative integers.

Returns a list of values from GEN such that each value was an element of indexes.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: range &key FROM TO BY INCLUSIVE

Create a generator that produces a series of numbers between FROM and TO with a step size of BY.

When INCLUSIVE is non NIL, then TO will be produced by the generator if it would be the last member of generate series.

E.g.

> (collect (range :to 10))

(0 1 2 3 4 5 6 7 8 9)

> (collect (range :to 10 :inclusive t))

(0 1 2 3 4 5 6 7 8 9 10)

> (collect (range :to 10 :by 2 :inclusive t))

(0 2 4 6 8 10)

> (collect (range :to 10 :by 3 :inclusive t))

(0 3 6 9)

If TO is NIL, then the generator produces an infinite series of values.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: repeater &rest ARGS

Creates a generator that produces an infinite series consisting in the the values of ARGS looped forever.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: seq SEQUENCE &key START

Turns a sequecne (a list, vector, string, etc) into a
generator. The resulting generator will generate exactly the members of the sequence.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: size GEN

Consumes GEN by calculating its size.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: take N GEN

Consumes GEN by collecting its first N values into a list

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: times N

Shorthand for (RANGE :TO N)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: truncate! N GEN

Shrinks a generator to generate a series of at most N values.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: zip! GEN &rest GENS

Is a shortcut for (MAP! #’LIST GEN1 GEN2 ...)

Package

gtwiwtg

Source

gtwiwtg.lisp (file)


Previous: , Up: Definitions   [Contents][Index]

5.2 Internal definitions


Next: , Previous: , Up: Internal definitions   [Contents][Index]

5.2.1 Macros

Macro: a-generator-class NAME SUPERS &rest SLOTS
Package

gtwiwtg

Source

gtwiwtg.lisp (file)


Next: , Previous: , Up: Internal definitions   [Contents][Index]

5.2.2 Functions

Function: all-clean GENS
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: all-different THINGS
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: all-good GENS
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: make-dirty G
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: make-keyword SYMB
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Function: sully-when-clean GENS
Package

gtwiwtg

Source

gtwiwtg.lisp (file)


Next: , Previous: , Up: Internal definitions   [Contents][Index]

5.2.3 Generic functions

Generic Function: dirty-p OBJECT
Generic Function: (setf dirty-p) NEW-VALUE OBJECT
Package

gtwiwtg

Methods
Method: dirty-p (GENERATOR! generator!)
Method: (setf dirty-p) NEW-VALUE (GENERATOR! generator!)

Indicates whether or not this generator has
generated any values yet, or if it should behave as if it has.

Source

gtwiwtg.lisp (file)

Generic Function: has-next-p GEN

Returns true if next can be called on the generator GEN.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Methods
Method: has-next-p (G stream-backed-generator!)
Method: has-next-p (G thunk-backed-generator!)
Method: has-next-p (G list-backed-generator!)
Method: has-next-p (G sequence-backed-generator!)
Method: has-next-p (G range-backed-generator!)
Method: has-next-p (G generator!) around
Generic Function: next GEN

Returns the next value of the generator GEN, if
available. Unspecified behavior if the GEN has been exhausted.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Methods
Method: next (G stream-backed-generator!)
Method: next (G thunk-backed-generator!)
Method: next (G list-backed-generator!)
Method: next (G sequence-backed-generator!)
Method: next (G range-backed-generator!)
Generic Function: stop GEN

Explicitly stops the generator. Specialize :after
methods to implement any clean up that needs to be done when the generator has been consumed.

Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Methods
Method: stop (G stream-backed-generator!) after
Method: stop (G thunk-backed-generator!) after
Method: stop (G generator!)
Generic Function: stopped-p OBJECT
Generic Function: (setf stopped-p) NEW-VALUE OBJECT
Package

gtwiwtg

Methods
Method: stopped-p (GENERATOR! generator!)
Method: (setf stopped-p) NEW-VALUE (GENERATOR! generator!)

Indicates whether or not this generator has been
explicitly stopped. All consumers explicitly stop the generators they consume.

Source

gtwiwtg.lisp (file)


Previous: , Up: Internal definitions   [Contents][Index]

5.2.4 Classes

Class: generator! ()
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Direct superclasses

standard-object (class)

Direct subclasses
Direct methods
Direct slots
Slot: dirty-p

Indicates whether or not this generator has
generated any values yet, or if it should behave as if it has.

Readers

dirty-p (generic function)

Writers

(setf dirty-p) (generic function)

Slot: stopped-p

Indicates whether or not this generator has been
explicitly stopped. All consumers explicitly stop the generators they consume.

Readers

stopped-p (generic function)

Writers

(setf stopped-p) (generic function)

Class: list-backed-generator! ()
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Direct superclasses

generator! (class)

Direct methods
Direct slots
Slot: list
Initargs

:list

Class: range-backed-generator! ()
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Direct superclasses

generator! (class)

Direct methods
Direct slots
Slot: at
Initargs

:at

Initform

0

Slot: to
Initargs

:to

Slot: by
Initargs

:by

Initform

1

Slot: comparator
Initargs

:comparator

Initform

(function <)

Class: sequence-backed-generator! ()
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Direct superclasses

generator! (class)

Direct methods
Direct slots
Slot: sequence
Initargs

:sequence

Slot: index
Initargs

:index

Class: stream-backed-generator! ()
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Direct superclasses

generator! (class)

Direct methods
Direct slots
Slot: stream
Initargs

:stream

Slot: reader
Initargs

:reader

Class: thunk-backed-generator! ()
Package

gtwiwtg

Source

gtwiwtg.lisp (file)

Direct superclasses

generator! (class)

Direct methods
Direct slots
Slot: next-p-fn
Initargs

:next-p-fn

Slot: next-fn
Initargs

:next-fn

Slot: stop-fn
Initargs

:stop-fn


Previous: , Up: Top   [Contents][Index]

Appendix A Indexes


Next: , Previous: , Up: Indexes   [Contents][Index]

A.1 Concepts

Jump to:   F   G   L  
Index Entry  Section

F
File, Lisp, gtwiwtg.asd: The gtwiwtg․asd file
File, Lisp, gtwiwtg/anaphora.lisp: The gtwiwtg/anaphora․lisp file
File, Lisp, gtwiwtg/gtwiwtg.lisp: The gtwiwtg/gtwiwtg․lisp file
File, Lisp, gtwiwtg/package.lisp: The gtwiwtg/package․lisp file

G
gtwiwtg.asd: The gtwiwtg․asd file
gtwiwtg/anaphora.lisp: The gtwiwtg/anaphora․lisp file
gtwiwtg/gtwiwtg.lisp: The gtwiwtg/gtwiwtg․lisp file
gtwiwtg/package.lisp: The gtwiwtg/package․lisp file

L
Lisp File, gtwiwtg.asd: The gtwiwtg․asd file
Lisp File, gtwiwtg/anaphora.lisp: The gtwiwtg/anaphora․lisp file
Lisp File, gtwiwtg/gtwiwtg.lisp: The gtwiwtg/gtwiwtg․lisp file
Lisp File, gtwiwtg/package.lisp: The gtwiwtg/package․lisp file

Jump to:   F   G   L  

Next: , Previous: , Up: Indexes   [Contents][Index]

A.2 Functions

Jump to:   (  
A   C   D   F   G   H   I   M   N   P   R   S   T   W   Z  
Index Entry  Section

(
(setf dirty-p): Internal generic functions
(setf dirty-p): Internal generic functions
(setf stopped-p): Internal generic functions
(setf stopped-p): Internal generic functions

A
a-generator-class: Internal macros
afold: Exported macros
afor: Exported macros
all-clean: Internal functions
all-different: Internal functions
all-good: Internal functions
argmax: Exported functions
argmin: Exported functions
average: Exported functions

C
collect: Exported functions
concat!: Exported functions

D
dirty-p: Internal generic functions
dirty-p: Internal generic functions

F
file-bytes: Exported functions
file-chars: Exported functions
file-lines: Exported functions
filter!: Exported functions
fold: Exported macros
for: Exported macros
from-input-stream: Exported functions
from-recurrence: Exported functions
from-thunk: Exported functions
from-thunk-times: Exported functions
from-thunk-until: Exported functions
Function, all-clean: Internal functions
Function, all-different: Internal functions
Function, all-good: Internal functions
Function, argmax: Exported functions
Function, argmin: Exported functions
Function, average: Exported functions
Function, collect: Exported functions
Function, concat!: Exported functions
Function, file-bytes: Exported functions
Function, file-chars: Exported functions
Function, file-lines: Exported functions
Function, filter!: Exported functions
Function, from-input-stream: Exported functions
Function, from-recurrence: Exported functions
Function, from-thunk: Exported functions
Function, from-thunk-times: Exported functions
Function, from-thunk-until: Exported functions
Function, indexed!: Exported functions
Function, inflate!: Exported functions
Function, inject!: Exported functions
Function, intersperse!: Exported functions
Function, make-dirty: Internal functions
Function, make-keyword: Internal functions
Function, map!: Exported functions
Function, maximum: Exported functions
Function, merge!: Exported functions
Function, minimum: Exported functions
Function, noise: Exported functions
Function, pick-out: Exported functions
Function, range: Exported functions
Function, repeater: Exported functions
Function, seq: Exported functions
Function, size: Exported functions
Function, sully-when-clean: Internal functions
Function, take: Exported functions
Function, times: Exported functions
Function, truncate!: Exported functions
Function, zip!: Exported functions

G
Generic Function, (setf dirty-p): Internal generic functions
Generic Function, (setf stopped-p): Internal generic functions
Generic Function, dirty-p: Internal generic functions
Generic Function, has-next-p: Internal generic functions
Generic Function, next: Internal generic functions
Generic Function, stop: Internal generic functions
Generic Function, stopped-p: Internal generic functions

H
has-next-p: Internal generic functions
has-next-p: Internal generic functions
has-next-p: Internal generic functions
has-next-p: Internal generic functions
has-next-p: Internal generic functions
has-next-p: Internal generic functions
has-next-p: Internal generic functions

I
indexed!: Exported functions
inflate!: Exported functions
inject!: Exported functions
intersperse!: Exported functions

M
Macro, a-generator-class: Internal macros
Macro, afold: Exported macros
Macro, afor: Exported macros
Macro, fold: Exported macros
Macro, for: Exported macros
Macro, with-generator: Exported macros
make-dirty: Internal functions
make-keyword: Internal functions
map!: Exported functions
maximum: Exported functions
merge!: Exported functions
Method, (setf dirty-p): Internal generic functions
Method, (setf stopped-p): Internal generic functions
Method, dirty-p: Internal generic functions
Method, has-next-p: Internal generic functions
Method, has-next-p: Internal generic functions
Method, has-next-p: Internal generic functions
Method, has-next-p: Internal generic functions
Method, has-next-p: Internal generic functions
Method, has-next-p: Internal generic functions
Method, next: Internal generic functions
Method, next: Internal generic functions
Method, next: Internal generic functions
Method, next: Internal generic functions
Method, next: Internal generic functions
Method, stop: Internal generic functions
Method, stop: Internal generic functions
Method, stop: Internal generic functions
Method, stopped-p: Internal generic functions
minimum: Exported functions

N
next: Internal generic functions
next: Internal generic functions
next: Internal generic functions
next: Internal generic functions
next: Internal generic functions
next: Internal generic functions
noise: Exported functions

P
pick-out: Exported functions

R
range: Exported functions
repeater: Exported functions

S
seq: Exported functions
size: Exported functions
stop: Internal generic functions
stop: Internal generic functions
stop: Internal generic functions
stop: Internal generic functions
stopped-p: Internal generic functions
stopped-p: Internal generic functions
sully-when-clean: Internal functions

T
take: Exported functions
times: Exported functions
truncate!: Exported functions

W
with-generator: Exported macros

Z
zip!: Exported functions

Jump to:   (  
A   C   D   F   G   H   I   M   N   P   R   S   T   W   Z  

Next: , Previous: , Up: Indexes   [Contents][Index]

A.3 Variables

Jump to:   A   B   C   D   I   L   N   R   S   T  
Index Entry  Section

A
at: Internal classes

B
by: Internal classes

C
comparator: Internal classes

D
dirty-p: Internal classes

I
index: Internal classes

L
list: Internal classes

N
next-fn: Internal classes
next-p-fn: Internal classes

R
reader: Internal classes

S
sequence: Internal classes
Slot, at: Internal classes
Slot, by: Internal classes
Slot, comparator: Internal classes
Slot, dirty-p: Internal classes
Slot, index: Internal classes
Slot, list: Internal classes
Slot, next-fn: Internal classes
Slot, next-p-fn: Internal classes
Slot, reader: Internal classes
Slot, sequence: Internal classes
Slot, stop-fn: Internal classes
Slot, stopped-p: Internal classes
Slot, stream: Internal classes
Slot, to: Internal classes
stop-fn: Internal classes
stopped-p: Internal classes
stream: Internal classes

T
to: Internal classes

Jump to:   A   B   C   D   I   L   N   R   S   T  

Previous: , Up: Indexes   [Contents][Index]

A.4 Data types

Jump to:   C   G   L   P   R   S   T  
Index Entry  Section

C
Class, generator!: Internal classes
Class, list-backed-generator!: Internal classes
Class, range-backed-generator!: Internal classes
Class, sequence-backed-generator!: Internal classes
Class, stream-backed-generator!: Internal classes
Class, thunk-backed-generator!: Internal classes

G
generator!: Internal classes
gtwiwtg: The gtwiwtg system
gtwiwtg: The gtwiwtg package
gtwiwtg.anaphora: The gtwiwtg․anaphora package

L
list-backed-generator!: Internal classes

P
Package, gtwiwtg: The gtwiwtg package
Package, gtwiwtg.anaphora: The gtwiwtg․anaphora package

R
range-backed-generator!: Internal classes

S
sequence-backed-generator!: Internal classes
stream-backed-generator!: Internal classes
System, gtwiwtg: The gtwiwtg system

T
thunk-backed-generator!: Internal classes

Jump to:   C   G   L   P   R   S   T