Created
August 12, 2019 15:09
-
-
Save wpcarro/831877eb875adaa02c59482d020b2b4d to your computer and use it in GitHub Desktop.
Basic implementation of a cycle data structure in Elisp.
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
| ;;; cycle.el --- Simple module for working with cycles. -*- lexical-binding: t -*- | |
| ;; Author: William Carroll <wpcarro@gmail.com> | |
| ;;; Commentary: | |
| ;; Something like this may already exist, but I'm having trouble finding it, and | |
| ;; I think writing my own is a nice exercise for learning more Elisp. | |
| ;;; Code: | |
| ;; `current-index' tracks the current index | |
| ;; `xs' is the original list | |
| (cl-defstruct cycle current-index xs) | |
| (defun cycle/from-list (xs) | |
| "Create a cycle from a list of `xs'." | |
| (make-cycle :current-index 0 | |
| :xs xs)) | |
| (defun next-index<- (lo hi x) | |
| "Returns the next index when moving downwards." | |
| (if (< (- x 1) lo) | |
| (- hi 1) | |
| (- x 1))) | |
| (defun next-index-> (lo hi x) | |
| "Returns the next index when moving upwards." | |
| (if (>= (+ 1 x) hi) | |
| lo | |
| (+ 1 x))) | |
| (defun cycle/prev (cycle) | |
| "Return the previous value in `cycle' and update `current-index'." | |
| (let* ((current-index (cycle-current-index cycle)) | |
| (next-index (next-index<- 0 (cycle/count cycle) current-index))) | |
| (setf (cycle-current-index cycle) next-index) | |
| (nth current-index (cycle-xs cycle)))) | |
| (defun cycle/next (cycle) | |
| "Return the next value in `cycle' and update `current-index'." | |
| (let* ((current-index (cycle-current-index cycle)) | |
| (length (cycle/count cycle)) | |
| (next-index (next-index-> 0 (cycle/count cycle) current-index))) | |
| (setf (cycle-current-index cycle) next-index) | |
| (nth current-index (cycle-xs cycle)))) | |
| (defun cycle/current (cycle) | |
| "Return the current value in `cycle/'." | |
| (nth (cycle-current-index cycle) (cycle-xs cycle))) | |
| (defun cycle/count (cycle) | |
| "Returns the lengtho of `xs' in `cycle'." | |
| (length (cycle-xs cycle))) | |
| (provide 'cycle) | |
| ;;; cycle.el ends here |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: make
next-index<-andnext-index->private (also consider better names for these.