Skip to content

Instantly share code, notes, and snippets.

@robertmaxwilliams
Created November 10, 2018 00:18
Show Gist options
  • Save robertmaxwilliams/9b7c922a0292ac0c72609dcb3d4e24a8 to your computer and use it in GitHub Desktop.
Save robertmaxwilliams/9b7c922a0292ac0c72609dcb3d4e24a8 to your computer and use it in GitHub Desktop.
How to do basic object oriented in common list. Only for fun, if you actually want OO, use CLOS.
(defun inverse-collatz (n)
"returns a list with one or two values that collatz to n"
(cons (* 2 n)
(let ((other-result (/ (- n 1) 3)))
(if (integerp other-result)
(list other-result)
nil))))
;; use lambda closure to access lexically scoped variable "starting-list"
(defun inverse-collatz-grower-maker (starting-list)
;; TODO put a "let" here for "self" so call between methods is possible
(list
(cons 'get-starting-list
#'(lambda ()
starting-list))
(cons 'set-starting-list
#'(lambda (new-val)
(setf starting-list new-val)))
(cons 'expand-n
#'(lambda (n)
(if (member n starting-list)
(setf starting-list
(remove-duplicates (append (inverse-collatz n) starting-list))))))))
(defun dot (alist key &rest args)
(apply (cdr (assoc key alist)) args))
;; minimal example of structure it works on
(dot (list (cons 'foo #'(lambda (x y) (+ x y)))) 'foo 4 2)
;; >> 6
(defvar foo1 (inverse-collatz-grower-maker '(1)))
;; >> foo1
(dot foo1 'get-starting-list)
;; >> (1)
(dot foo1 'set-starting-list '(1 2 3))
;; >> (1 2 3)
(dot foo1 'expand-n 1)
;; >> (0 1 2 3) ;; 0 should be redacted ;(
(dot foo1 'expand-n 2)
;; >> (4 0 1 2 3)
(dot foo1 'expand-n 3)
;; >> (6 4 0 1 2 3)
(dot foo1 'expand-n 4)
;; >> (8 6 4 0 1 2 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment