Skip to content

Instantly share code, notes, and snippets.

View auxiliaire's full-sized avatar

Viktor Daróczi auxiliaire

View GitHub Profile
@auxiliaire
auxiliaire / either.php
Created April 21, 2022 19:36
The `either` function in PHP
function either(...$args) {
return self::curry(function(callable $f, callable $g, Either $e) {
return match (true) {
$e->isLeft() => $f($e->value),
default => $g($e->value)
};
})(...$args);
}
@auxiliaire
auxiliaire / gregorian.erl
Created May 2, 2021 17:18
Some basic functions for a Gregorian calendar
-module(gregorian).
-export([
days/0,
months/0,
dayTuples/0,
monthTuples/0,
dayOfWeek/1,
monthOfYear/1,
isLeap/1,
daysOfMonth/2,
@auxiliaire
auxiliaire / hello.erl
Created May 2, 2021 12:31
Say Hello to Erlang
-module(hello).
-export([
hello/0,
]).
%% Hello world
hello() ->
io:format("Hello, world!~n").
@auxiliaire
auxiliaire / maybe.php
Created April 9, 2021 15:57
The `maybe` function in PHP
function maybe(...$args) {
return curry(fn(mixed $v, callable $f, Maybe $m) =>
match (true) {
$m->isNothing() => $v,
default => call_user_func($f, $m->get())
}
)(...$args);
}
@auxiliaire
auxiliaire / Maybe.php
Created April 9, 2021 13:37
Maybe in PHP
class Maybe {
public function __construct(private $value = null) { }
public function isNothing(): bool {
return $this->value === null;
}
public function isJust(): bool {
return !$this->isNothing();
@auxiliaire
auxiliaire / prop-helper.php
Created April 7, 2021 19:45
Implement `prop` for objects in PHP
function _getProp(string $prop, object $obj) {
$r = new ReflectionClass($obj);
$hasProp = $r->hasProperty($prop);
$getter = 'get' . ucfirst($prop);
$hasGetter = $r->hasMethod($getter);
return match (true) {
$hasProp && $r->getProperty($prop)->isPublic() => $obj->$prop,
$hasGetter && $r->getMethod($getter)->isPublic() => $obj->$getter(),
default => null
};
@auxiliaire
auxiliaire / prop.php
Created April 7, 2021 19:40
Implement `prop` in PHP
function prop(...$args) {
return self::curry(fn(string $prop, array $obj) => match (true) {
is_array($obj) && array_key_exists($prop, $obj) => $obj[$prop],
default => null
})(...$args);
}
@auxiliaire
auxiliaire / init.php
Created April 7, 2021 19:04
Implement `init` in PHP
function init(array | string $xs) {
return match (true) {
is_string($xs) && !empty($xs) => substr($xs, 0, -1),
is_array($xs) && !empty($xs) => array_slice($xs, 0, -1),
default => null
};
}
@auxiliaire
auxiliaire / last.php
Created April 7, 2021 19:03
Implement `last` in PHP
function last(array | string $xs) {
return match (true) {
is_string($xs) && !empty($xs) => substr($xs, -1),
is_array($xs) && !empty($xs) => $xs[count($xs) - 1],
default => null
};
}
@auxiliaire
auxiliaire / drop.php
Created April 7, 2021 18:28
Implement `drop` in PHP
function drop(...$args) {
return curry(fn($n, $xs) => match (true) {
is_string($xs) => substr($xs, $n),
is_array($xs) => array_slice($xs, $n),
default => null
})(...$args);
}