Skip to content

Instantly share code, notes, and snippets.

View duarten's full-sized avatar
🤷‍♂️

Duarte Nunes duarten

🤷‍♂️
View GitHub Profile
public interface IBufferPool
{
byte[] TakeBuffer(int size);
void ReturnBuffer(byte[] buffer);
}
public class BufferPoolWithLeakDetection : IBufferPool
{
public class MemoryLeakException : Exception
{
@duarten
duarten / LazyQsort.clj
Created June 19, 2011 22:03
A lazy quick sort
(ns sort
(:use clojure.test))
(defn qsort [xs]
"Sorts the specified sequence using the quick sort algorithm"
(if-let [[pivot & rest] (seq xs)]
(let [smaller? #(< % pivot)]
(lazy-cat (qsort (filter smaller? rest))
[pivot]
(qsort (remove smaller? rest))))))
# I want this method in ruby-core
def let
yield
end
def fib(i)
let do |n = 1, result = 0|
if i == -1
result
else
@duarten
duarten / AsyncEnumerator.cs
Created August 1, 2011 20:30
AsyncEnumerator redux
public static class AsyncEnumerator
{
//
// Asynchronously but sequentially executes all tasks returned by the specified enumerator.
//
public static Task Run(this IEnumerator<Task> source,
CancellationToken token = default(CancellationToken))
{
return runInternal<object>(source, token);
@duarten
duarten / commatize.clj
Created February 7, 2012 18:27 — forked from unclebob/commatize
A function to format a number with commas
(defn commatize [n]
(->> n str reverse (partition-all 3) (interpose \,) flatten reverse (apply str)))
class C
{
static C()
{
// Let's run the initialization on another thread!
var thread = new System.Threading.Thread(Initialize);
thread.Start();
thread.Join();
}
static void Initialize() { }
@duarten
duarten / find.clj
Created February 14, 2013 11:47
A function to search Hiccup data structures.
(def ^{:private true} not-nil? (comp not nil?))
(defprotocol Matcher
"Protocol for types that can be used to search a Hiccup data structure."
(matches [this elem]))
(defn- comp-name [x y]
(and (not-nil? y) (= (name x) (name y))))
(extend-protocol Matcher
@duarten
duarten / Partitions.scala
Created April 22, 2013 09:32
For a given list, returns all the possible partitions of that list.
type Partition[A] = List[List[A]]
def partitions[A](xs: List[A]): List[Partition[A]] = l match {
case Nil => Nil
case h :: Nil => List(List(List(h)))
case h :: t =>
val ps = partitions(t)
ps.map(List(h) :: _) ::: ps.flatMap(interpolate(h, _))
}
@duarten
duarten / conditional.c
Last active December 16, 2015 17:19
Conditionals without control flow instructions.
int conditional(int x, int y, int z) {
int nx = !x - 1;
return (nx & y) | (~nx & z);
}
@duarten
duarten / nSumCombinations.hs
Created May 13, 2013 17:22
Given a list of integrals, find all combinations of `n` values in the list such that their sum is `s`.
nSumCombinations :: (Integral a) => Int -> a -> [a] -> [[a]]
nSumCombinations _ _ [] = []
nSumCombinations 1 s xs = map (\x -> [x]) $ filter (== s) xs
nSumCombinations n s (x:xs) = (map (x:) $ nSumCombinations (n - 1) (s - x) xs) ++ (nSumCombinations n s xs)