Skip to content

Instantly share code, notes, and snippets.

View jjant's full-sized avatar
💥
λ

Julian Antonielli jjant

💥
λ
View GitHub Profile
@jjant
jjant / flatten.js
Created January 5, 2018 18:51
Simple Array flatten implementation in js
// Takes an array with possible nested arrays, and returns a **new** flat array.
const flatten = array =>
array.reduce(
(flattened, elem) =>
flattened.concat(Array.isArray(elem) ? flatten(elem) : elem),
[]
);
// From here on below we have only test utilities
const test = (testedFunc, input, expectedOutput, comparator) => {
@jjant
jjant / IO.js
Created April 13, 2018 23:58
IO Monad implementation in javascript for pure IO.
const GET_LINE = Symbol('GET_LINE');
const PUT_LINE = Symbol('PUT_LINE');
const RETURN = Symbol('RETURN');
const NOTHING = 'NOTHING!!';
const unit = undefined;
// Primitive IO actions, these are pure functions.
const returnIO = a => ({
type: RETURN,
flatMap: f => f(a),
@jjant
jjant / cont.hs
Created June 13, 2018 21:22
Continuation Type Definition
newtype Cont r a = Cont { runCont :: (a -> r) -> r }
myCont :: Cont r Int
myCont = Cont (\k -> k (10 + 30))
double :: Int -> Int
double x = x * 2
(runCont myCont) double -- 80
{-# LANGUAGE InstanceSigs #-}
instance Functor (Cont r) where
fmap :: (a -> b) -> Cont r a -> Cont r b
-- Equivalent to
-- fmap :: (a -> b) -> ((a -> r) -> r) -> ((b -> r) -> r)
fmap f (Cont g) = Cont $ \k -> g (\a -> k (f a))
myCont2 :: Cont Int Int
myCont2 = Cont (\k -> k 0 + k 15)
plus1 :: Int -> Int
plus1 x = x + 1
runCont myCont2 plus1 -- plus1 0 + plus1 15 = 1 + 16 = 17
plus100 :: Int -> Int
plus100 x = x + 100
instance Monad (Cont r) where
return x = Cont (\k -> k x)
-- (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b
(Cont c) >>= f = Cont $ \k -> c (\x -> runCont (f x) k)
myCont = Cont (\k -> k 0 + k 15)
runCont myCont id -- id 0 + id 15 = 15
myCont2 = myCont >>= (\x -> Cont ($ (x * 2))
runCont myCont2 id -- 30. Wait, what?
k0Plusk15 = \k -> k 0 + k 15
myCont = Cont k0Plusk15 -- Extracted the function for ease of notation later below.
myCont2 = myCont >>= (\x -> return (x * 2))
= (Cont k0Plusk15) >>= (\x -> Cont ($ (x * 2)))
= Cont $ \k' -> k0Plusk15 (\x -> runCont (Cont ($ (x * 2))) k')
= Cont $ \k' -> k0Plusk15 (\x -> ($ (x * 2)) k')
= Cont $ \k' -> k0Plusk15 (\x -> k' (x * 2))
= Cont $ \k' -> k0Plusk15 (\x -> k' (x * 2))