Skip to content

Instantly share code, notes, and snippets.

@pwm
pwm / queue.hs
Created June 26, 2017 11:03
Haskell Queue
-- http://www.randomhacks.net.s3-website-us-east-1.amazonaws.com/2007/02/08/haskell-queues-without-pointers/
{-# OPTIONS_GHC -Wall #-}
module Queue where
-- A queue holding values of type 'a'.
data Queue a = Queue [a] [a]
deriving (Show)
-- Create a new queue.
@pwm
pwm / r30.php
Last active July 10, 2017 22:00
Rule 30
<?php
/**
* Run it: php r30.php
* Run it with a custom number of rows: php r30.php <number>
* Have fun :)
*/
function createRows($numRows, $rule) {
$getNextRow = function ($currRow) use ($rule) {
$nextRow = [0, 0];
@pwm
pwm / antree.php
Last active July 11, 2017 14:36
ANTree vs NTree
<?php
declare(strict_types = 1);
class ANTree
{
const TERMINAL_NODE = 'LEAF';
private $routeTree = [];
public function add(array $segments): void
{
@pwm
pwm / trampoline.php
Created October 27, 2017 14:15
Trampolining tail-recursive functions
<?php
declare(strict_types=1);
$trampoline = function (callable $f) {
return function (...$args) use ($f) {
while (is_callable($f)) {
$f = $f(...$args);
}
return $f;
};
@pwm
pwm / aoc2017.hs
Last active December 4, 2017 13:42
AOC 2017
-- read string into list
input = map (\x -> read [x]::Int)
-----------
-- Day 1 --
-----------
-- part 1
f xs = sum $ map fst $ filter (\(x,y) -> x == y) $ zip xs $ tail $ (\xs -> xs ++ [head xs]) xs
@pwm
pwm / DisjointSet.php
Created December 15, 2017 00:01
Disjoint Set
<?php
declare(strict_types=1);
class DisjointSet
{
private $parent = [];
private $rank = [];
public function makeSet(int $i): void
{
@pwm
pwm / sieve.php
Last active December 23, 2017 21:09
Sieve of Eratosthenes
<?php
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
function sieve(int $n): array {
$a = array_fill(2, $n - 1, true);
for ($i = 2, $iMax = floor(sqrt($n)); $i <= $iMax; $i++) {
if ($a[$i] === true) {
for ($j = $i ** 2; $j <= $n; $j += $i) {
$a[$j] = false;
}
}
@pwm
pwm / bs_1_list.hs
Last active January 1, 2018 19:32
Binary Search - List, Array, UArray, Vector, UVector
{-# OPTIONS_GHC -Wall #-}
module Main (main) where
import Data.List (unfoldr)
bs :: [Int] -> Int -> Int
bs ys key = binarySearch ys 0 (length ys - 1) key where
binarySearch xs l h k
| h < l = -1
| k == x = m
@pwm
pwm / careful_with_immutability.php
Created March 8, 2018 14:29
Careful with immutability
<?php
declare(strict_types=1);
class X {
private $s;
public function __construct(string $s) { $this->s = $s; }
public function getS(): string { return $this->s; }
}
class Y {
private $x;
@pwm
pwm / maybe.php
Created March 10, 2018 15:49
Some Maybe stuff
<?php
declare(strict_types=1);
// ((a, ...) -> z) -> a -> ... -> z
function curry(callable $f, ...$args) {
return function (...$partialArgs) use ($f, $args) {
return (function ($args) use ($f) {
return \count($args) < (new \ReflectionFunction($f))->getNumberOfRequiredParameters()
? curry($f, ...$args)
: $f(...$args);