• Top
    • Documentation
    • Books
    • Boolean-reasoning
    • Projects
    • Debugging
    • Std
    • Proof-automation
    • Macro-libraries
    • ACL2
      • Theories
      • Rule-classes
      • Proof-builder
      • Recursion-and-induction
      • Hons-and-memoization
      • Events
      • Parallelism
      • History
      • Programming
        • Defun
        • Declare
        • System-utilities
        • Stobj
        • State
        • Mutual-recursion
        • Memoize
        • Mbe
        • Io
        • Defpkg
        • Apply$
        • Loop$
        • Programming-with-state
        • Arrays
        • Characters
        • Time$
        • Defmacro
        • Loop$-primer
        • Fast-alists
        • Defconst
        • Evaluation
        • Guard
        • Equality-variants
        • Compilation
        • Hons
        • ACL2-built-ins
        • Developers-guide
        • System-attachments
        • Advanced-features
        • Set-check-invariant-risk
        • Numbers
        • Efficiency
        • Irrelevant-formals
        • Introduction-to-programming-in-ACL2-for-those-who-know-lisp
        • Redefining-programs
        • Lists
          • Member
          • Append
          • List
          • Nth
          • Len
          • True-listp
          • String-listp
          • Nat-listp
          • Character-listp
          • Symbol-listp
          • True-list-listp
          • Length
          • Search
          • Intersection$
          • Union$
          • Remove-duplicates
          • Position
          • Update-nth
          • Take
          • Nthcdr
          • Set-difference$
          • Subsetp
          • No-duplicatesp
          • Concatenate
          • Remove
          • Remove1
          • Intersectp
          • Endp
          • Keyword-value-listp
          • Integer-listp
          • Reverse
            • Nrev
              • Nrev-set-hint
              • Nrev-finish
              • Nrev-copy
              • Nrev-push
              • Nrev-fix
              • Nrev-demo
              • Nrev-stobj
              • Nrev2
              • Nrev-append
              • With-local-nrev
              • Nrev$c
            • Rev
            • Std/lists/reverse
            • Hons-reverse
          • Add-to-set
          • List-utilities
          • Set-size
          • Revappend
          • Subseq
          • Make-list
          • Last
          • Lists-light
          • Boolean-listp
          • Butlast
          • Pairlis$
          • Substitute
          • Count
          • Keyword-listp
          • List*
          • Eqlable-listp
          • Pos-listp
          • Integer-range-listp
          • Rational-listp
          • Evens
          • Atom-listp
          • ACL2-number-listp
          • Typed-list-utilities
          • Odds
          • List$
          • Listp
          • Standard-char-listp
          • Last-cdr
          • Pairlis
          • Proper-consp
          • Improper-consp
          • Pairlis-x2
          • Pairlis-x1
          • Merge-sort-lexorder
          • Fix-true-list
          • Real-listp
        • Invariant-risk
        • Errors
        • Defabbrev
        • Conses
        • Alists
        • Set-register-invariant-risk
        • Strings
        • Program-wrapper
        • Get-internal-time
        • Basics
        • Packages
        • Oracle-eval
        • Defmacro-untouchable
        • <<
        • Primitive
        • Revert-world
        • Unmemoize
        • Set-duplicate-keys-action
        • Symbols
        • Def-list-constructor
        • Easy-simplify-term
        • Defiteration
        • Fake-oracle-eval
        • Defopen
        • Sleep
      • Operational-semantics
      • Real
      • Start-here
      • Debugging
      • Miscellaneous
      • Output-controls
      • Macros
      • Interfacing-tools
    • Interfacing-tools
    • Hardware-verification
    • Software-verification
    • Math
    • Testing-utilities
  • Reverse

Nrev

A safe mechanism for implementing something like nreverse, for writing tail-recursive functions that use less memory by avoiding the final reverse step.

Motivation

To avoid stack overflows, you sometimes need tail-recursive executable versions of your functions. These tail-recursive functions often produce their elements in the reverse of the desired order. For instance, here is a basic, tail-recursive map:

(defun map-exec (x acc)
  (if (atom x)
      acc
    (map-exec (cdr x) (cons (f (car x)) acc))))

But this produces elements in the wrong order. To correct for this, you might explicitly reverse the elements, e.g.,:

(defun map (x)
  (mbe :logic (if (atom x)
                  nil
                (cons (f (car x)) (map (cdr x))))
       :exec (reverse (map-exec x nil))))

This successfully avoids stack overflows, but since reverse is applicative, this approach allocates twice as many conses as the naive, non tail-recursive version.

In Common Lisp, we could avoid this overhead using nreverse, a destructive routine that can reverse a list in-place by swapping pointers. But since nreverse is destructive, it wouldn't be sound to just make it generally available in ACL2.

Even so, we would like to have something like nreverse that would allow us to write tail-recursive versions of map without having to allocate double the conses. In principle, it is okay to use nreverse here because we are only tampering with fresh conses that are not reachable from anywhere else in the program. (Well, that's almost true; if map-exec were memoized, then we could get into trouble.)

Solution

nrev is, we believe, a safe mechanism for writing tail-recursive functions that can (at your option) avoid this double consing by using destructive, under-the-hood operations.

Without trust tags, nrev is roughly on par with the ordinary reverse based solution:

  • Memory — same as reverse, i.e., still twice as many as the non tail-recursive version.
  • Runtime — perhaps around 1.3x worse than reverse due to the ACL2::stobj overhead.

With a trust tag, nrev is roughly on par with the nreverse solution:

  • Memory — same as nreverse, i.e., avoids the double consing problem.
  • Runtime — perhaps around 1.25x worse than nreverse due to the ACL2::stobj overhead, but still faster than a traditional reverse based solution.

Loading nrev

For the pure ACL2 (no trust tags) version, you can use:

(include-book "centaur/nrev/pure" :dir :system)

For the optimized (trust tags) version, you can instead load:

(include-book "centaur/nrev/fast" :dir :system)

Note that it's perfectly fine to start with the pure book and then load the fast version later. Loading the fast version will "retroactively" optimize all functions that are based on nrev.

Using nrev

These books implement an abstract stobj called nrev. The logical story is that nrev is just a list. The fundamental operation on nrev is nrev-push, which logically conses "onto the right," like rcons. Once you have pushed the desired elements, you can get them back out in queue order using nrev-finish.

See nrev-demo for a basic example.

Subtopics

Nrev-set-hint
Set a candidate list to try and preserve existing conses when finishing an nrev.
Nrev-finish
Final step to extract the elements from an nrev.
Nrev-copy
Slow operation to copy the current contents of nrev, without destroying it.
Nrev-push
Fundamental operation to extend nrev with a new element.
Nrev-fix
Identity function for nrev.
Nrev-demo
Short demonstration of using nrev for a basic map function.
Nrev-stobj
Definition of the nrev abstract stobj.
Nrev2
An extra nrev created with ACL2::defstobj-clone.
Nrev-append
Add several elements into nrev at once.
With-local-nrev
Wrapper for with-local-stobj for common cases of using nrev.
Nrev$c
The concrete nrev stobj.