Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Created August 12, 2019 15:09
Show Gist options
  • Select an option

  • Save wpcarro/831877eb875adaa02c59482d020b2b4d to your computer and use it in GitHub Desktop.

Select an option

Save wpcarro/831877eb875adaa02c59482d020b2b4d to your computer and use it in GitHub Desktop.
Basic implementation of a cycle data structure in Elisp.
;;; 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
@wpcarro
Copy link
Author

wpcarro commented Aug 12, 2019

TODO: make next-index<- and next-index-> private (also consider better names for these.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment