Skip to content

Instantly share code, notes, and snippets.


Keybase proof

I hereby claim:

  • I am cushon on github.
  • I am cushon ( on keybase.
  • I have a public key whose fingerprint is CA45 8B81 BFFF F2BE 04CF 6802 A2C1 0047 21A7 7AAF

To claim this, I am signing this object:

cushon /
Last active Aug 29, 2015
For when you absolutely positively have to create an enum.
static <T extends Enum<T>> T getOrCreateEnum(Class<T> enumType,
String name, int ordinal) {
try {
return Enum.valueOf(enumType, name);
} catch (IllegalArgumentException createFascimileInstead) {
try {
T enumValue = (T) getUnsafe().allocateInstance(enumType);
Field nameField = Enum.class.getDeclaredField("name");
cushon /
Created Mar 21, 2011
Does a list contain duplicate references?
(define (list-uniq l)
(define t (make-hasheq))
(define (check l)
(or (empty? l)
(not (cons? l))
(and (cons? l)
(not (hash-ref t l #f))
(hash-set! t l #t)
(check/list l)))))
cushon /
Created Mar 19, 2011
Fibonacci implementation using a memoizing y-combinator.
(define Y
(λ (f)
(define t (make-hash))
((λ (x) (x x))
(λ (x) (f (λ a (hash-ref! t a (λ () (apply (x x) a)))))))))
(define fib
(Y (λ (f) (λ (n)
(if (< n 2) n
(+ (f (- n 1)) (f (- n 2))))))))
cushon /
Created Mar 18, 2011
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
cushon /
Created Mar 18, 2011
Subset and permutations without explicit recursion. The permutation implementation uses a fixed point combinator.
(define (subsets l)
(foldl (lambda (x y)
(foldr (lambda (u v) (cons (cons x u) (cons u v)))
'() y))
'(()) l))
(define permutations
(lambda (l)
(((lambda (f)
((lambda (x) (f (lambda arg (apply (x x) arg))))
cushon /
Created Mar 1, 2011
Lazy generation of Hamming numbers in PLT Racket
(define (hamming)
(lcons 1 (lfoldr merge (map (lambda (p) (map (lambda (x) (* p x)) (hamming)))
(lazy-list 2 3 5)))))
; lazy-list library
(define-syntax lcons
(syntax-rules ()
((_ a b) (lambda (f) (f a (lambda () b))))))
(define (lazy-list . x)
(foldr (lambda (x y) (lcons x y)) '() x))
cushon /
Created Mar 1, 2011
foldl implemented with foldr
(define (foldl f b l)
((foldr (lambda (x y) (lambda (b) (y (f x b)))) values l) b))