Skip to content

Instantly share code, notes, and snippets.

@jld
jld / gist:1818271
Created February 13, 2012 16:57
Euler Project Problem 14 solution, written on a Monday morning while mostly asleep
; http://projecteuler.net/problem=14
(define (eu14 m)
(let ((memo (make-vector m #f))
(best-l 0)
(best-i 0))
(define (up n a)
(cond
((= n 1) a)
((and (< n m) (vector-ref memo n)) => (lambda (x) (+ a x)))
@jld
jld / randfloat.rs
Created July 17, 2012 04:59
Wait for rand::gen_f64 to generate a number greater than 1.0
import rand::rng;
fn main() {
let mut count : u64 = 0;
let rng = rand::seeded_rng(~[17]);
loop {
let r = rng.gen_f64();
if r > 1.0f64 {
io::println(#fmt("%s > 1.0 (after %? tries)",
float::to_str_exact(r as float, 16), count));
@jld
jld / nfa.rs
Created August 10, 2012 03:05
Nondeterministic automaton thing. Type-checks only with the commented-out ascription.
enum pc = u32;
struct state<S: copy> {
let state: S;
let pc: pc;
let idx: uint;
}
trait success<S: copy, R> {
fn succeed(state: &S) -> R;
@jld
jld / gist:3502438
Created August 28, 2012 19:00
Rust vector shortening
import vec::*;
fn truncate<T>(&v: ~[const T], newlen: uint) {
let oldlen = len(v);
assert(newlen <= oldlen);
unsafe {
for uint::range(newlen, oldlen) |i| {
let _dropped <- *ptr::mut_addr_of(v[i]);
}
unsafe::set_len(v, newlen);
@jld
jld / gist:3518971
Created August 29, 2012 21:06
Sorted vector uniquification
import core::cmp::{Eq,Ord};
mod exhibitA {
fn unique<T: copy Eq>(&v: ~[mut T]) {
let mut i_dst = 0, i_src = 1;
let ln = v.len();
if ln < 1 { return; }
while i_src < ln {
if !v[i_src].eq(v[i_dst]) {
i_dst += 1;
@jld
jld / gist:3590199
Created September 1, 2012 22:49
Traits on vectors do strange things.
import to_bytes::{IterBytes,iter_le_bytes_2,iter_be_bytes_2};
enum thing = uint;
impl thing : IterBytes {
fn iter_le_bytes(f: to_bytes::Cb) { (*self).iter_le_bytes(f) }
fn iter_be_bytes(f: to_bytes::Cb) { (*self).iter_be_bytes(f) }
}
enum stuff1 = ~[thing];
impl stuff1 : IterBytes {
@jld
jld / gist:3595887
Created September 2, 2012 08:29
In which Brzozowski derivatives are computed.
stuff = e13
e0 = ∅
e1 = ε
e2 = !e0
e3 = '/'
e4 = '*'
e5 = e3 + e4
e6 = e4 + e3
e7 = e3 + e2
e8 = e4 + e7
fn foo<T>(&dst: @const T, &src: @const T) {
dst = src;
}
fn main()
{
let mut r_imm = @0;
let mut r_mut = @mut 0;
foo(r_imm, r_mut);
io::println(fmt!("r_imm = %?", r_imm));
@jld
jld / gist:4482393
Created January 8, 2013 09:13
In which the vec library has a bad day.
fn main() {
let v : ~[[i8 * 0]] = ~[];
io::println(fmt!("%?", v.len()));
}
@jld
jld / gist:4577482
Created January 20, 2013 09:30
Fun With Macros
pub struct SetupRequest {
byte_order: u8,
protocol_major_version: u16,
protocol_minor_version: u16,
authorization_protocol_name: ~[u8],
authorization_protocol_data: ~[u8],
}
struct_io!{
SetupRequest;
copy byte_order;