Skip to content

Instantly share code, notes, and snippets.

@nvanderw
nvanderw / Stack.hs
Created August 22, 2012 04:56
Stack-based programming using monad transformers
import Control.Monad
import Control.Monad.Identity (runIdentity)
import Control.Monad.Error
import Control.Monad.State.Lazy
import Data.Maybe (listToMaybe)
-- |Monad transformer which stores a stack internally
type StackT s m = StateT [s] m
@nvanderw
nvanderw / functors.py
Created August 21, 2012 07:19
Typeclass stuff in Python
import itertools
# Monad instance on a Python iterator, very similar to Haskell's list monad.
# In general, Haskell typeclass instances can be regarded as dictionaries which
# map the implemented function to its implementation. For a good explanation of
# this, see Philip Wadler's "Faith, Evolution, and Programming Languages"
# lecture. What this means for us is that we can write a function whose type
# signature in Haskell would be:
# Monad m => f m
#
@nvanderw
nvanderw / fibs.hs
Created August 4, 2012 03:08
Polymorphic fibonacci generation using monad transformers
import Control.Monad
import Control.Monad.State.Lazy
-- Simple way to get Fibonacci numbers using monad transformers
fibT :: (Monad m, Num a) => StateT a (StateT a m) ()
fibT = get >>= \x -> lift get >>= \y -> put y >> (lift . put $ x + y)
-- Get the nth Fibonacci number
fib :: Num a => Int -> a
fib n = execState (execStateT (replicateM_ n fibT) 0) 1
@nvanderw
nvanderw / gist:2963459
Created June 21, 2012 02:18
Exercise Set 7.1
import System.Environment
sumSquares :: (Integral a) => a -> a
sumSquares n = n*(n+1)*(2*n+1) `div` 6
sumCubes :: (Integral a) => a -> a
sumCubes n = ((n^2 + n) `div` 2)^2
main = do
args <- getArgs
@nvanderw
nvanderw / pre-receive
Created June 15, 2012 23:52
A pre-receive hook for blacklisting certain objects
#!/usr/bin/env bash
# Blacklist commit 1abfdd7
root=$(awk '{print $2}')
objects=$(git rev-list --objects $root | awk '{print $1}')
echo $objects | grep 1abfdd7cb8c67ead50757ea596aa0f01b0ab1389 > /dev/null
if [[ $? -eq 0 ]]
then