Skip to content

Instantly share code, notes, and snippets.

mem = {}
def collatz_len(n):
if n < 2:
return 1
if n not in mem:
chain = 1 + collatz_len(n/2 if n%2 == 0 else 3*n + 1)
mem[n] = chain
return mem[n]
def f(k, n):
'''
k indistinct bucket,
n (n > k) balls,
each bucket must have at least one ball,
how many ways are there to put n balls in k buckets?
'''
if k == 1:
# Only one way to put things in one bucket
return 1
import Control.Monad (liftM)
import Data.IORef (IORef, newIORef, modifyIORef', readIORef)
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad.Trans.Except (ExceptT, Except, except, runExcept, mapExcept, throwE)
import Control.Monad.IO.Class (liftIO)
data IVal
= IInt Int
{-# LANGUAGE DeriveFunctor #-}
import Control.Monad.Free
data MThing next
= MItem String next
| MEnd
deriving (Show, Functor)
doThing :: Free MThing ()
data IOOp
= EndProgram
| ReadLine (String -> IOOp)
| WriteLine String IOOp
runOp :: IOOp -> IO ()
runOp EndProgram = return ()
runOp (ReadLine f) = do
line <- getLine
with open('img.ppm', 'w') as outf:
outf.write('P6 256 256 255 ')
for i in xrange(256):
for j in xrange(256):
outf.write('%c%c%c' % (i ^ j, i ^ (255 - j), (i+j) % 256))
import re, sys # this file requires python 3
def parse(tokens):
stack = ([], None)
for t in tokens:
if t == '(':
stack = ([], stack)
elif t == ')':
(finished_list, stack) = stack
stack[0].append(finished_list)
elif not t.startswith(';;'):
import Control.Concurrent
main = do
setNumCapabilities 4
result <- parallelDoWork 38 4
--result <- doWork 38 4
putStrLn $ show result
parallelDoWork n m = do
resultMVars <- mapM (\_ -> forkWork n) [1..m]

Erlang Cheat Sheet

(this is a work in progress)

Running Erlang

Getting the interpreter in ubuntu: sudo apt-get install erlang. To get native compliation capability, also install erlang-base-hipe.

Starting the interpreter: erl. To exit: Ctrl-g then q enter.

import Control.Monad (liftM)
import Control.Monad.Except
type MyMonad = ExceptT String IO
successVal :: MyMonad Int
successVal = return 123
errVal :: MyMonad Int
errVal = throwError "this is an error"