Skip to content

Instantly share code, notes, and snippets.

@mathias
Created July 15, 2012 23:11
Show Gist options
  • Save mathias/3119102 to your computer and use it in GitHub Desktop.
Save mathias/3119102 to your computer and use it in GitHub Desktop.
Land of Lisp Chapter 2
(ns chapter_2_clj.core)
; here I use atoms as a replacement for chapter 2's globals
(def small (atom 1))
(def big (atom 100))
(defn average [& all]
(quot (apply + all) (count all)))
; here's a version that uses arguments
(defn guess-my-number-w-args [small, big]
(average small big))
(defn guess-my-number []
(average @small @big))
(defn smaller []
(reset! big (dec (guess-my-number)))
(guess-my-number))
(defn bigger []
(reset! small (inc (guess-my-number)))
(guess-my-number))
(defn start-over []
(reset! small 1)
(reset! big 100)
(guess-my-number))
; Guess My Number Game
; Land of Lisp - Chapter 2
(defparameter *small* 1)
(defparameter *big* 100)
; Lispers like to mark their globals with "earmuffs" as a convention.
; defvar won't overwrite previous values of a global variable like defparamter will:
(defvar *foo* 5)
*foo*
; -> 5
(defvar *foo* 6)
*foo*
; -> 5
(defun guess-my-number ()
(ash (+ *small* *big*) -1))
; the built-in Lisp function ash looks at a number in binary form, and then
; shifts its binary bits to the left or right, dropping any bits lost in the
; process. For example, the number 11 written in binary is 1011. We can move
; the bits in this number to the left with ash by using 1 as the second
; argument
(ash 11 1)
; -> 22
; my attempt at a dumberer guess-my-number function that doesn't rely on understanding ash function:
(defun dumb-guess-my-number ()
(round (+ *small* *big*) 2))
(defun smaller ()
(setf *big* (1- (guess-my-number)))
(guess-my-number))
(defun bigger ()
(setf *small* (1+ (guess-my-number)))
(guess-my-number))
(defun start-over ()
(defparameter *small* 1)
(defparameter *big* 100)
(guess-my-number))
; local variables:
(let ((a 5)
(b 6))
(+ a b))
; local functions:
(flet ((f (n)
(+ n 10)))
(f 5))
(flet ((f (n)
(+ n 10))
(g (n)
(- n 3)))
(g (f 5)))
; -> 12
; we need the labels function if we want to call local functions out of order:
(labels ((a (n)
(+ n 5))
(b (n)
(+ (a n) 6)))
(b 10))
; -> 21
; because we call a from inside b, we need to use labels so that the two
; functions know about each other.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment