Skip to content

Instantly share code, notes, and snippets.

@cqfd
cqfd / coro.js
Last active August 29, 2015 14:22
Coroutines and promises in Node.
// Run with `node --harmony coro.js`
"use strict";
const Promise = require('bluebird');
// Takes a function*, `g`, that yields promises.
// Returns a promise that resolves to `g`'s eventual return value.
var coro = function(gStar) {
const pending = Promise.pending();
@cqfd
cqfd / Phantoms.hs
Created April 14, 2015 21:00
Phantom type evaluator example
module Phantom (
ei, eb, plus, iff, -- Smart constructors
eval -- Evaluation
) where
data Expr a = EI Int
| EB Bool
| Plus (Expr Int) (Expr Int)
| If (Expr Bool) (Expr a) (Expr a)
deriving Show
@cqfd
cqfd / Gadts.hs
Created April 14, 2015 20:59
GADTs evaluator example
{-# LANGUAGE GADTs #-}
module Gadt where
import Data.Monoid
data Expr a where
EI :: Int -> Expr Int
EB :: Bool -> Expr Bool
Plus :: Expr Int -> Expr Int -> Expr Int
@cqfd
cqfd / Generators.md
Last active November 7, 2022 20:53
Generators in JavaScript and Haskell

ES6. Using yield and yield*.

function* a() {
  var i = yield "first thing from a";
  var j = yield "second thing from a";
  return [i, j];
}

function* b() {
@cqfd
cqfd / Trie.hs
Last active August 29, 2015 14:17
Trie example
module Trie where
import Prelude hiding (lookup)
import Data.Maybe
import qualified Data.Map as M
data Trie = Trie (M.Map Char Trie) Bool
empty :: Trie
empty = Trie M.empty False
@cqfd
cqfd / FreeGenerators.hs
Last active August 29, 2015 14:17
Free Python-style generators
module FreeGenerators where
import Control.Monad.Trans
import Control.Monad.Trans.Free
data YieldF i o r = YieldF o (i -> r)
instance Functor (YieldF i o) where
fmap f (YieldF o k) = YieldF o (f . k)
@cqfd
cqfd / Generators.hs
Last active August 29, 2015 14:17
Sketch towards Python-style generators in Haskell
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Generators where
import Prelude hiding (take, filter)
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
@cqfd
cqfd / Straws.hs
Last active August 29, 2015 14:17
Sketches for a baby version of Pipes.
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
{-# LANGUAGE Rank2Types #-}
module Tuyau where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import System.IO (isEOF)
@cqfd
cqfd / Family.hs
Last active August 29, 2015 14:16
Notes for a Hacker School talk on functors, applicatives, etc.
{-# LANGUAGE DeriveFunctor #-}
module Family where
import Control.Applicative
import Data.Monoid
-- Functors
--
-- Lift a function (a -> b) to (f a -> f b)
@cqfd
cqfd / Applicatives.hs
Created March 5, 2015 16:30
Free applicative functors in terms of liftA2.
{-# LANGUAGE ExistentialQuantification #-}
import Control.Applicative
import Data.Functor.Identity
data Ap f a = Pure a
| forall x y. LiftA2 (x -> y -> a) (f x) (Ap f y)
instance Functor f => Functor (Ap f) where
fmap f (Pure a) = Pure (f a)