Skip to content

Instantly share code, notes, and snippets.

@cushon
Created March 18, 2011 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cushon/875762 to your computer and use it in GitHub Desktop.
Save cushon/875762 to your computer and use it in GitHub Desktop.
Higher order list manipulation without recursion. Foldr is implemented with a fixed point combinator; foldl, filter, and map are implemented with foldr. The use of 'define' isn't necessary, but avoids copy-pasta.
(define foldr
((lambda (f)
((lambda (x) (f (lambda arg (apply (x x) arg))))
(lambda (x) (f (lambda arg (apply (x x) arg))))))
(lambda (g)
(lambda (f b l)
(if (empty? l) b
(f (car l) (g f b (cdr l))))))))
(define foldl
(lambda (f b l)
((foldr (lambda (x y) (lambda (b) (y (f x b))))
values
l) b)))
(define filter
(lambda (p l)
(foldr (lambda (x y) (if (p x) (cons x y) y))
'() l)))
(define map
(lambda (f l) (foldr (lambda (x y) (cons (f x) y)) '() l)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment