Skip to content

Instantly share code, notes, and snippets.

View keybase.md

Keybase proof

I hereby claim:

  • I am cushon on github.
  • I am cushon (https://keybase.io/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
cushon / getOrCreateEnum.java
Last active Aug 29, 2015
For when you absolutely positively have to create an enum.
View getOrCreateEnum.java
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
cushon / list-uniq.ss
Created Mar 21, 2011
Does a list contain duplicate references?
View list-uniq.ss
(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))
(begin
(hash-set! t l #t)
(check/list l)))))
@cushon
cushon / memo-combinator.ss
Created Mar 19, 2011
Fibonacci implementation using a memoizing y-combinator.
View memo-combinator.ss
(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
cushon / higher-order-list.ss
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.
View higher-order-list.ss
(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
cushon / subset-permutation.ss
Created Mar 18, 2011
Subset and permutations without explicit recursion. The permutation implementation uses a fixed point combinator.
View subset-permutation.ss
(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
cushon / hamming.ss
Created Mar 1, 2011
Lazy generation of Hamming numbers in PLT Racket
View hamming.ss
(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
cushon / foldl.ss
Created Mar 1, 2011
foldl implemented with foldr
View foldl.ss
(define (foldl f b l)
((foldr (lambda (x y) (lambda (b) (y (f x b)))) values l) b))
You can’t perform that action at this time.