Skip to content

Instantly share code, notes, and snippets.

@mark-d-holmberg
Created September 14, 2011 15:52
Show Gist options
  • Save mark-d-holmberg/1216931 to your computer and use it in GitHub Desktop.
Save mark-d-holmberg/1216931 to your computer and use it in GitHub Desktop.
Tail Recursion in Clojure
Mark Holmberg, Dixie State College of Utah
CS 3520, Programming Languages
14 Sept. 2011
(defn foldl [f sofar lst]
(if (empty? lst) sofar
(foldl f(f (first lst) sofar) (rest lst))))
(defn foldr [f sofar lst]
(if (empty? lst) sofar
(f (first lst) (foldr f sofar (rest lst)))))
(defn mymap [f lst] (foldr (fn [elt sofar] (cons (f elt) sofar)) '() lst))
//some tests
(foldr + 0 '(1 2 3 4 5))
(cons 4 '(5 6))
(foldl cons '() '(1 2 3 4 5 6))
(foldr cons '() '(1 2 3 4 5 6))
(foldl * 1 '(1 2 3 4 5 6))
(apply * 1 '(1 2 3 4 5 6))
(mymap #(* % %) '(1 2 3 4 5 6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment