Skip to content

Instantly share code, notes, and snippets.

@arkeet
arkeet / ZPhi.hs
Created April 23, 2015 22:38
Z[φ]
module ZPhi where
-- | When @a@ is the integers, this represents the ring Z[φ] of numbers of the form a + bφ, where φ = (1 + √5)/2 is the golden ratio. @'ZPhi' a b@ corresponds to the number a + bφ.
data ZPhi a = ZPhi !a !a
deriving (Eq,Show)
-- | @'fib' n@ computes the n'th Fibonacci number in Θ(log |n|) time. Negative arguments are permitted.
fib :: (Integral i, Num a) => i -> a
fib n = let ZPhi _ r = phiPow n in r
@arkeet
arkeet / GenericApplicative.hs
Last active August 29, 2015 14:16
Using Generic to write Applicative/Monad methods
{-# LANGUAGE TypeOperators, FlexibleContexts, DeriveGeneric #-}
import Control.Applicative
import GHC.Generics
import Data.Monoid
-------- Needed for making instances using Generic machinery
-- Orphan instances are bad though.
-- Nullary product
@arkeet
arkeet / Improve.hs
Last active December 23, 2015 15:29
Improved semigroups
import Data.Semigroup
data Improve a = Improve (a -> a) a
instance Semigroup (Improve a) where
~(Improve a' a) <> ~(Improve b' b) = Improve (a' . b') (a' b)
improve :: Semigroup a => a -> Improve a
improve a = Improve (a <>) a
@arkeet
arkeet / Network.hs
Last active December 23, 2015 02:39
module Game.TcgMud.Network
( runServer
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.STM (atomically, TVar, newTVarIO, readTVar, modifyTVar')
import Control.Monad (forever)
import Network (HostName, withSocketsDo, listenOn, PortNumber, PortID(PortNumber), accept)
import System.IO (Handle, hGetLine, hPrint, hClose)
import Control.Exception (finally)
@arkeet
arkeet / Monadoid.hs
Last active December 15, 2015 15:49
{-# LANGUAGE PolyKinds, GADTs, FlexibleInstances #-}
import Data.Char (ord)
import Control.Arrow (first)
-- Basic class definitions.
class Functor2 (f :: κ -> λ -> * -> *) where
fmap2 :: (a -> b) -> (f i j a -> f i j b)
@arkeet
arkeet / monadlens.hs
Created December 15, 2012 14:21
Lens operators for monads. This is really awful.
import Control.Lens
import Control.Lens.Classes
import Control.Lens.Internal
import Control.Monad.Reader
import Control.Monad.State
import Data.IORef
-- I'm not sure what "something" is supposed to be.
-- The second argument to x is a total hack.