Skip to content

Instantly share code, notes, and snippets.

View fgalassi's full-sized avatar

Federico Galassi fgalassi

View GitHub Profile
% The beauty of the right programming paradigm.
% Conway's Game of life in 4 lines of Octave code.
function new = life(board)
neighbours = conv2(board, [1 1 1; 1 0 1; 1 1 1], 'same')
new = neighbours == 3 | (neighbours == 2 & board)
end
% Create a 100x100 board and run the game in a GUI
def square_root(x, guess)
puts "guessing: #{guess}"
if guess * guess == x
guess
else
new_guess = (guess + x / guess) / 2
square_root(x, new_guess)
end
end
@fgalassi
fgalassi / map.js
Created June 8, 2017 14:45
Map in very functional es6 style
let map = (func, [head, ...tail]) => head === undefined ? [] : [func(head), ...map(func, tail)]
map(n => n + 1, [1, 2, 3])
// [2, 3, 4]
/**
* The `navigate` function takes a `Path` string that
* can contain parameter names using the `users/:username`
* syntax. Type it so that the `params` object provided
* as the second argument always contains a key for each variable
* in the `Path`.
*/
namespace parseUrlParams {
declare function navigate<U extends string>(
path: U,
// This is tricky because you cannot do Str extends `${infer Before}${UnionOfSep}${infer After}` ...
type Split<Str, UnionOfSep extends string, CurrentWord extends string = "", Output extends string[] = []> =
Str extends `${infer First}${infer Rest}`
? First extends UnionOfSep
? Split<Rest, UnionOfSep, "", [...Output, CurrentWord]>
: Split<Rest, UnionOfSep, `${CurrentWord}${First}`, Output>
: [...Output, CurrentWord];