Tags » Common Lisp

When to define a function rather than a local variable

Define a local variable when you want to use the same value in different ways.

Define a function when you want to compute different values in the same way.

Common Lisp

(if) vs (cond)

(if) requires a test AND an action for T but an action for NIL is not required. If the test returns NIL, and there’s no action, (if) will return NIL. 62 more words

Common Lisp

Predicates vs Non-Predicates

Predicates like (listp) or (zerop) or (null) or (equal) are considered predicates because they will always return T or NIL, no matter what type of arguments are provided. 32 more words

Common Lisp

The results of evaluating logical functions

T is an atom. T is not a list.

NIL is an atom and a list; Only NIL and ‘() evluate to NIL. 23 more words

Common Lisp

Quoted vs Unquoted

(list ‘x a) means create a list with atom ‘x’ with the VARIABLE A

(list ‘(a b) (c ‘d)) means create a list with list ‘(a b) with the result of calling operator ‘c’ with atom ‘d’

Common Lisp

MuSh: Multi-Shebang Scripting

MuSh is a super simple meta-scripting language for parsing multiple shebang statements that invoke different interpretors. Why would you want to do this? I have no idea. 459 more words

Computer Science

Bridge Hands

The bridge hands problem on programming praxis in Common Lisp.

(defvar deck
 (loop for n from 0 to 51
 collect n))

(defun shuffle (deck &optional results)
 (if (not deck)
 (let* ((num-cards (length deck))
 (card (nth (random num-cards) deck)))
 (shuffle (remove card deck) (cons card results)))))

(defun deal (shuffled-deck)
 (loop for i from 0 to 3
 for deck = shuffled-deck then (subseq deck 13)
 for hand = (subseq deck 0 13)
 collect hand))

(defconstant empty-hand
 (list (list) (list) (list) (list)))

(defun add-to-hand (my-hand card)
 (let ((suit (floor card 13)))
 (setf (nth suit my-hand) (cons card (nth suit my-hand)))

(defun build-hand (card-list)
 (let ((my-hand (copy-tree empty-hand)))
 (loop for card in card-list do
 (setf my-hand (add-to-hand my-hand card))
 finally (return my-hand))))

(defun shuffle-deal-build ()
 (loop for card-list in (deal (shuffle deck))
 collect (build-hand card-list)))

(defun translate-card (card)
 (let ((card-strings
 #("2" "3" "4" "5" "6" "7" "8" "9" "10" "J" "Q" "K" "A")))
 (aref card-strings (rem card 13))))

(defun print-suit (card-list suit)
 (let ((sorted (sort card-list #'>))
 (suit-strings #("C: " "D: " "H: " "S: ")))
 (format t "~a" (aref suit-strings suit))
 (loop for card in sorted do
 (format t "~a " (translate-card card)))))

(defun print-hand (my-hand)
 (loop for suit from 3 downto 0 do
 (print-suit (nth suit my-hand) suit)
 (format t "~%"))))

(defun print-all-hands (shuffled-deck)
 for hand in shuffled-deck
 for tag in '("NORTH" "EAST" "SOUTH" "WEST")
 (format t "~a~%" tag)
 (print-hand hand)
 (format t "~%"))))



… 9 more words