Skip to content

Instantly share code, notes, and snippets.

@cushon
cushon / list-uniq.ss
Created March 21, 2011 01:17
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))
(begin
(hash-set! t l #t)
(check/list l)))))
@cushon
cushon / memo-combinator.ss
Created March 19, 2011 08:45
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
cushon / subset-permutation.ss
Created March 18, 2011 07:51
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
cushon / higher-order-list.ss
Created March 18, 2011 08:01
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
cushon / hamming.ss
Created March 1, 2011 08:26
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
cushon / foldl.ss
Created March 1, 2011 07:17
foldl implemented with foldr
(define (foldl f b l)
((foldr (lambda (x y) (lambda (b) (y (f x b)))) values l) b))

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 August 29, 2015 13:58
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");