Skip to content

Instantly share code, notes, and snippets.

@flazz
Created July 3, 2011 02:27
Show Gist options
  • Save flazz/1061898 to your computer and use it in GitHub Desktop.
Save flazz/1061898 to your computer and use it in GitHub Desktop.
lambda based data structures
(ns lambda-list)
;;; basic linked list using lambdas
; construct a pair containing x and y
(defn pair [x y]
(fn [b]
(if b x y)))
; construct a singleton list containing x
(defn singleton [x]
(pair x nil))
; return the head of a list
(defn head [pair]
(pair true))
; return the tail of a list
(defn tail [pair]
(pair false))
;;; everything below is gravy
; true if l is a singleton otherwise false
(defn singleton? [l]
(nil? (tail l)))
; map a function over a list
(defn map [f l]
(if (nil? l)
nil
(pair
(f (head l))
(map f (tail l)))))
; fold a list with a function and an initial value
(defn fold [f acc l]
(if (nil? l)
acc
(fold f
(f acc (head l))
(tail l))))
; interleave x in l
(defn interleave [x l]
(if (singleton? l)
l
(pair (head l)
(pair x
(interleave x (tail l))))))
; convert a list to a string
(defn show [l]
(str
"("
(fold str "" (interleave " " l))
")"))
; a list to test the functions
(def the-test-list
(pair "a"
(pair "b"
(singleton "c"))))
(println "basic show:\t" (show the-test-list))
(println "map .length:\t" (show (map (fn [s] (. s length))
the-test-list)))
(ns lambda-map)
;;; functional mapping using lambdas
(defn new-map [name value]
(fn [k]
(if (= name k)
value
nil)))
(defn update-map [m name value]
(fn [k]
(if (= name k)
value
(m k))))
(def the-test-map
(update-map
(update-map
(update-map
(new-map 'foo 55)
'bar 66)
'baz 77)
'foo 44))
(println "test map:" (the-test-map 'foo))
(println "test map:" (the-test-map 'bar))
(println "test map:" (the-test-map 'baz))
(println "test map:" (the-test-map 'xxx))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment