Last active
August 3, 2018 10:53
-
-
Save Willmo36/cf77c02bb7c62ddc9b5d6d52d4000b1f to your computer and use it in GitHub Desktop.
Simple implementation of BatchedQueue from "Purely Functional Data Structures"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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