Skip to content

Instantly share code, notes, and snippets.

View beoliver's full-sized avatar

Benjamin Oliver beoliver

View GitHub Profile
@beoliver
beoliver / tries.c
Last active November 7, 2015 01:07
basic trie
//
// tries.c
// chitchat
//
// Created by Ben Oliver on 06/11/15.
// Copyright © 2015 Ben Oliver. All rights reserved.
//
// assume that we allow 8 char sequences from an alphabet of 26 characters
// there are 26 ^ 8 possible sequences 208,827,064,576
class Memoize(object):
def __init__(self, f):
self.f = f
self.computed = {}
def __call__(self, *args):
xs = self.computed.get(args)
if xs :
return xs
def memoize(f):
computed = {}
def memoized(*args):
xs = computed.get(args)
if xs :
return xs
else :
value = f(*args)
import java.util.Random;
/**
* Created by boliver on 03/06/15.
*/
public class Main {
public static void main(String args[]) {
Container value = new Container();
@beoliver
beoliver / balance.scm
Last active August 29, 2015 14:20
Scheme closure balance example
(define (make-balance)
(let ((balance 0))
(define add-method
(lambda (value) (set! balance (+ balance value))))
(define get-method
(lambda () balance))
(define sub-method
(lambda (value)
(if (<= value balance)
(set! balance (- balance value))
(define (make-counter-1)
(let ((counter 0))
(lambda ()
(set! counter (+ counter 1))
counter)))
(define (make-counter-2)
(define counter 0)
(lambda ()
(set! counter (+ counter 1))
@beoliver
beoliver / scope.scm
Created May 10, 2015 19:03
let vs define
> (define (foo)
(let ((xs '(1 2 3)))
(define (f)
(set! xs 0))
(f)
xs))
> (foo)
0
@beoliver
beoliver / scheme_thunks.scm
Created May 10, 2015 18:21
scheme thunks (delayed evaluation)
;; delay and force are defined in r5rs,
;; but if we were defining them for ourselves
(define-syntax my-delay
(syntax-rules ()
((_ expr)
(lambda () expr))))
(define (my-force expr)
@beoliver
beoliver / gist:5e89180b864c01fcbc19
Last active August 29, 2015 14:20
the basics principles of set! in scheme
(require r5rs)
(define xs '(1 2 3 4 5)) ;; xs is a list of numbers
xs
(set! xs "a list of numbers") ;; xs is now "a list of numbers"
xs
(define (update-1 arg)
(set! arg "this has only changed the value of 'arg' within 'update-1'")
arg)
@beoliver
beoliver / Scheme_set-nth!.scm
Last active August 29, 2015 14:20
Scheme set-nth!
(require r5rs)
(define (set-nth! n xs x)
(cond ((null? xs) (error "index out of bounds"))
((eq? n 0) (set-car! xs x))
(#t (set-nth! (- n 1) (cdr xs) x))))