Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Last active August 3, 2018 10:53
Show Gist options
  • Save Willmo36/cf77c02bb7c62ddc9b5d6d52d4000b1f to your computer and use it in GitHub Desktop.
Save Willmo36/cf77c02bb7c62ddc9b5d6d52d4000b1f to your computer and use it in GitHub Desktop.
Simple implementation of BatchedQueue from "Purely Functional Data Structures"
//BatchedQueue implementation from Chirs Okasaki's "Purely Functional Data Structures"
class Queue<A> {
constructor(public readonly f: A[], public readonly t: A[]) {}
}
export const empty = new Queue([], []);
export const isEmpty = <A>(q: Queue<A>) => q.f.length === 0;
/**
* Maintain the invariant: If f is empty, so is t
*/
const checkf = <A>(q: Queue<A>) => {
if (q.f.length > 0) return q;
const f = [...q.t].reverse();
return new Queue(f, []);
};
export const snoc = <A>(a: A) => (q: Queue<A>) => checkf(new Queue(q.f, [a, ...q.t]));
export const head = <A>(a: A) => (q: Queue<A>) => q.f[0]; //use an option type here
export const tail = <A>(q: Queue<A>) => checkf(new Queue(q.f.slice(1), q.t));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment