Blog Archive

Tuesday, January 01, 2008

Constraint synonyms in Haskell

Hello folks, and happy new year!

Earlier today I found myself writing the same sequence of long constraints on my type-signatures over and over again in a Haskell program I was working on. The program is still in flux, so that means the constraints may still change. As all of the functions call each-other, they need to have a similar set of constraints on their type signatures.

This means as the program evolves, I'll need to make a lot of similar changes all over the source file. I'm pretty lazy, so that doesn't sound like fun to me. At first I thought I could do something like this with regular type synonyms, but that requires all functions to share their entire type, not just a set of constraints.

There are a few ways I could've solved this problem:
  • Don't use type signatures
    I'm not using any fancy type-level hacks, so the compiler doesn't really need them. But I like having them to prove to myself that I really do know what my code does, and to provide better error messages.
  • CPP Macros
    I haven't tried this one - I just thought of it while writing this
  • Type Classes
    Which is what this post is about


Let's say I have a number of functions whose type signatures are along the lines of:
> myFunc :: (Eq b, Show b, MyClass b, MyOtherClass b) => Int -> String -> b -> b

and I don't like typing the (Eq b, Show b, MyClass b, MyOtherClass b) part over and over again. I can define a typeclass which captures all of those constraints:
> class (Eq b, Show b, MyClass b, MyOtherClass b) => MyConstraints b

along with a rule to populate the class:
> instance (Eq b, Show b, MyClass b, MyOtherClass b) => MyContraints b

I can now re-write the type-signature for myFunc as follows:
> myFunc :: MyConstraints b => Int -> String -> b -> b


This works for the following reasons:
  • Memebership in the class "MyConstraints" implies membership in all of the other classes, due to the constraint on the class defintion.
  • Every type which satisfies the constraints is a member of the "MyConstraints" class.


As another check, if you load the module defining myFunc into GHCi and ask for its type at the interactive prompt, it will report it as
myFunc :: (Eq b, Show b, MyClass b, MyOtherClass b) => Int -> String -> b -> b

Which is exactly what I wanted.

Saturday, December 01, 2007

Backwards State, or: The Power of Laziness

There's been a recent discussion of Automatic Differentiation in Haskell recently, which somehow found me reading Jerzy Karczmarczuk's paper "Lazy Time Reversal, and Automatic Differentiation," which then cited Philip Wadler's "The essence of functional programming" for the introduction of the backwards state monad, which I reproduce here because I think it's neat.

I'm going to assume that you're familiar with the Haskell state monad - in summary an action in the state monad is a function of the previous state, and produces a result paired with the next state.

The backwards state monad differs from this in that the flow of the state through the execution is revere to the flow of the results - that is, an action in the backwards state monad takes in the final value of the state and produces a result and the initial value.

This post is literate Haskell post - you should be able to copy and past it into a .lhs file and play with it in a Haskell interpreter. I use GHCi.

To that end, here's some of the up-front boilerplate so this all works:

> {-# LANGUAGE FlexibleInstances,
> MultiParamTypeClasses,
> RecursiveDo
> #-}
> import Data.List
> import Control.Monad.State

An Example


Here's the exercise: Given a tree of items, transform the tree to a tree of Ints such that each element is mapped to an Int, starting at 0. If an element occurs more than once in the tree, it must be mapped to the same Int each time.

The solution given in Control.Monad.State.Lazy does a walk of the tree, and carries around a list of all of the elements seen so far using the state monad. Each node is mapped to its position in this list. That is, the first node seen is mapped to 0, the second to 1, etc..

But what if I wanted to switch that up? What if wanted the last node seen in the walk mapped to 0, the second to last mapped to 1, and so on? How much would I need to change in the already existing solution given in Control.Monad.State.Lazy?

Not much! I'd just need to use the backwards state monad, where the state flows backwards through the thread of execution.

This is what the modified solution would look like:

> data Tree a = Nil | Node a (Tree a) (Tree a) deriving (Show, Eq)
> type Table a = [a]

> numberTree :: Eq a => Tree a -> StateB (Table a) (Tree Int)
> numberTree Nil = return Nil
> numberTree (Node x t1 t2)
> = do num <- atomically $ numberNode x
> nt1 <- numberTree t1
> nt2 <- numberTree t2
> return (Node num nt1 nt2)
> where
> numberNode :: Eq a => a -> State (Table a) Int
> numberNode x
> = do table <- get
> (newTable, newPos) <- return (nNode x table)
> put newTable
> return newPos

> nNode:: (Eq a) => a -> Table a -> (Table a, Int)
> nNode x table
> = case elemIndex x table of
> Nothing -> (table ++ [x], length table)
> Just i -> (table, i)
And an evaluation function:

> numTree :: (Eq a) => Tree a -> Tree Int
> numTree t = evalStateB (numberTree t) []
Some test data:

> testTree = Node "Zero" (Node "One" (Node "Two" Nil Nil) (Node "One" (Node "Three" Nil Nil) Nil)) Nil
Executing numTree testTree will produce the output:
Node 3 (Node 1 (Node 2 Nil Nil) (Node 1 (Node 0 Nil Nil) Nil)) Nil
Which is exactly what we wanted!

This code is almost exactly the same as the solution given to the in-order problem in the source to Control.State.Lazy, the only changes are the use of the function evalStateB instead of the familiar evalState, and the use of the function atomically, and the StateB monad. The implementation of these will be explained bellow.

First the API, then the implementation.

The API


We have the new monad StateB s, where s is the type of the stored state.

StateB s is an instance of MonadState s, so get and put are as expected.

There is also:

> -- runStateB :: StateB s a -> s -> (a, s)
> evalStateB :: StateB s a -> s -> a
> execStateB :: StateB s a -> s -> s

which should look familiar. The trick is that the state s passed in to these functions is the final state, and the state returned is the initial state. In the example above, remember that the last element seen in the walk was given the first label, and the first element seen in the walk was given the last.

The default implementation of modify in Control.Monad.State.Class is implemented as follows:

-- modify :: MonadState s m => (s -> s) -> m ()
-- modify f = do
-- s <- get
-- put (f s)
In the StateB monad, this code will bottom-out, because of the circular data dependency of the two monadic actions - in the backwards state monad, (>>=) passes the result forward and the state backwards, which means that the above code has a nice loop where the first line grabs the updated state from the second line and tries to pass it in as an argument to the second line.

To make this work, we need a version of modify specific to StateB:

> modifyB :: (s -> s) -> StateB s ()
But if you want to modify the state and return the result, you'll need something more sophisticated:

> atomically :: State s a -> StateB s a
atomically converts an action under the normal state monad to a single action under StateB, allowing you do do complex updates to the state easily without bottoming out (using mdo notation also works).

Implementation


The base of the implementation is taken directly from Wadler's paper.

The StateB monad is almost the same as the State monad - each action of type a is a function of type \s -> (a,s). The difference is in the implementation of (>>=).

Let's start with the monad:

> newtype StateB s a = StateB {runStateB :: s -> (a,s)}

> instance Monad (StateB s) where
> return = StateB . unitS
> (StateB m) >>= f = StateB $ m `bindS` (runStateB . f)
Because wrapping and unwrapping the newtype annoys me, all of that is confined to the exported functions (like return and (>>=)). The functions that deal directly with the underlying type all have an 'S' suffix.

> m `bindS` k = \s2 -> let (a, s0) = m s1
> (b, s1) = k a s2
> in (b, s0)

> unitS a = \s2 -> (a, s2)
As you can see, the passed in state is acted on by the RHS of bindS, the intermediate state is consumed by the LHS, and the LHS produces the final state, s0. It looks too simple to work, but it does.
And the other API functions:

> execStateB m = snd . runStateB m

> evalStateB m = fst . runStateB m

> modifyB = StateB . modify'
> where modify' f = \s -> ((), f s)

> atomically = StateB . runState
Just for funsies:

> instance Functor (StateB s) where
> fmap f m = StateB $ mapS f (runStateB m)

> mapS f m = \s -> let (a, s') = m s in (f a, s')

> instance MonadState s (StateB s) where
> get = StateB get'
> where get' = \s -> (s,s)
>
> put = StateB . put'
> where put' s = const ((),s)

> instance MonadFix (StateB s) where
> mfix = StateB . mfixS . (runStateB .)

> mfixS f = \s2 -> let (a,s0) = (f b) s1
> (b,s1) = (f a) s2
> in (b,s0)

The transformer


Now a treat for those of you still paying attention. I haven't really tested this, but it looks like it should work and that's good enough for me. A lot of this is in the style of the sources for Control.Monad.State.Lazy.

> newtype StateBT s m a = StateBT {runStateBT :: s -> m (a,s)}

> unitST a = \s -> return (a,s)

> m `bindST` k = \s2 -> mdo ~(a,s0) <- m s1
> ~(b,s1) <- k a s2
> return (b,s0)

> execStateBT :: Monad m => StateBT s m a -> s -> m s
> execStateBT m s = do ~(_,s') <- runStateBT m s
> return s'

> evalStateBT :: Monad m => StateBT s m a -> s -> m a
> evalStateBT m s = do ~(a,_) <- runStateBT m s
> return a

> modifyBT :: Monad m => (s -> s) -> StateBT s m ()
> modifyBT = StateBT . modify'
> where modify' f = \s -> return ((),f s)

> atomicallyT :: Monad m => State s a -> StateBT s m a
> atomicallyT m = StateBT $ \s-> return $ runState m s

> atomicallyTM :: Monad m => StateT s m a -> StateBT s m a
> atomicallyTM = StateBT . runStateT

> mapST f m = \s -> do ~(a,s') <- m s
> return (f a,s')

> liftST m = \s -> do a <- m
> return (a,s)

> mfixST f = \s2 -> mdo ~(a,s0) <- (f b) s1
> ~(b,s1) <- (f a) s2
> return (b,s0)

> instance Monad m => Functor (StateBT s m) where
> fmap f m = StateBT $ mapST f (runStateBT m)

> instance MonadFix m => Monad (StateBT s m) where
> return = StateBT . unitST
> (StateBT m) >>= f = StateBT $ m `bindST` (runStateBT . f)
> fail = StateBT . const . fail

> instance MonadTrans (StateBT s) where
> lift = StateBT . liftST

> instance MonadFix m => MonadState s (StateBT s m) where
> get = StateBT get'
> where get' = \s -> return (s,s)
>
> put = StateBT . put'
> where put' s = const $ return ((),s)

> instance MonadFix m => MonadFix (StateBT s m) where
> mfix = StateBT . mfixST . (runStateBT .)

Monday, July 23, 2007

ICFP '07 Post-Mortem: IV

My friend Creighton and I entered the ICFP programming competition this year, we didn't make it very far, but then again we didn't spend as much time on it as last year. That's the way it goes.

I'm posting this in the hopes that someone can point out our bug. Please, help me!

This is our main module to convert DNA to RNA. If you're familiar with this years contest (and Haskell, I suppose) it should be reasonably comprehensible. I hope. If not, please let me know.
====================
Execute.lhs



> {-# OPTIONS -fglasgow-exts #-}

> module Execute where

> import DNA
> import Control.Monad.State
> import Data.List
> import System.IO
> import System.Environment
> import Data.Maybe
> import Maybe


I don't know that I've ever even tested our "main" method, maybe Creighton has. Almost all of our testing was done by loading the Testing module into GHCI.


> main :: IO ()
> main = do
> prefile:dnafile:_ <- getArgs
> prefix <- (openFile prefile ReadMode) >>= hGetContents
> dna <- (openFile dnafile ReadMode) >>= hGetContents
> let (World rna _ ) = execState execute (World [] (prefix++dna))
> print rna
> return ()


Here are our datatypes for the template items and pattern items. Everywhere the spec uses the Template datatype, that translates to [Template] in our implementation (and similarly for Pattern). Otherwise, these are pretty much straight from the spec.


> data Template = TBase Char | NL Int Int | N Int
> deriving Show

> data Pattern = Base Char | Skip Int | Search DNA | GOpen | GClose
> deriving Show


Most of the interesting stuff happens in the state monad, and this is our state!
DNA is of type String, and RNA is of type [DNA].


> data World = World RNA DNA
> deriving (Show, Eq)


These next few function operate on our state, they let us read DNA and write RNA. They'll get used all over the place.


> peekDNA :: (MonadState World m, Integral a) => a -> m [Char]
> peekDNA n = do World _ dna <- get
> return $ genericTake n dna

> popDNA :: (MonadState World m, Integral a) => a -> m [Char]
> popDNA n = do World a dna <- get
> put $ World a (genericDrop n dna)
> return $ genericTake n dna

> pushRNA :: MonadState World m => [Char] -> m ()
> pushRNA rna = do World rnas a <- get
> put $ World (rna:rnas) a


This is the Big Deal DNA to RNA function. The idea is that you give this to execState along with a World containing no RNA and the input DNA, and you'll get back a World containing the output RNA. The "main" function above has an example of this.


> execute :: MonadState World m => m ()
> execute = runMaybeT execute' >> return ()


The function execute' is run under the MaybeT monad transformer so that we can short-circuit the process from any of our functions by calling fail, which acts like finish () in the spec.

The function execute' looks almost exactly like in the spec. The reversals are in hopes that lots of pre-pending plus one big reverse is quicker that a lot of small post-pendings.


> execute' :: MonadState World m => m ()
> execute' = do p <- liftM reverse pattern
> t <- liftM reverse template
> matchreplace p t >> execute'


> pattern :: MonadState World m => m [Pattern]
> pattern = pattern' 0 []


Again, if you're familiar with the function pattern in the contest spec, this shouldn't look at all unfamiliar. Tail recursion is used to keep track of how match pattern is built up so far, and the current level.


> pattern' :: MonadState World m => Int -> [Pattern] -> m [Pattern]
> pattern' x ps = do
> base <- popDNA 1
> case base of
> "C" -> pattern' x ((Base 'I'):ps)
> "F" -> pattern' x ((Base 'C'):ps)
> "P" -> pattern' x ((Base 'F'):ps)
> otherwise -> do
> base' <- popDNA 1
> case (base,base') of
> ("I","C") -> pattern' x ((Base 'P'):ps)
> ("I","P") -> do
> n <- nat
> pattern' x ((Skip n):ps)
> ("I","F") -> do
> popDNA 1
> s <- consts
> pattern' x ((Search s):ps)
> otherwise -> do
> base'' <- popDNA 1
> case (base,base',base'') of
> ("I","I","P") -> pattern' (x+1) ((GOpen):ps)
> ("I","I","C") -> if x==0 then return ps else pattern' (x-1) ((GClose):ps)
> ("I","I","F") -> if x==0 then return ps else pattern' (x-1) ((GClose):ps)
> ("I","I","I") -> (popDNA 7 >>= pushRNA) >> pattern' x ps
> otherwise -> fail ""

> template :: MonadState World m => m [Template]
> template = template' []


Again, this shouldn't look unfamiliar to anyone who's spent time on the contest. And again, tail recurion is used to build up the template. In retrospect I probably didn't need to pass the current list in as a param, but hey, it's done. I guess I've bought into the "tail recursion as a replacement for state" meme. I'll need to break that habit - it isn't very Haskell-ish.


> template' :: MonadState World m => [Template] -> m [Template]
> template' ts = do base <- popDNA 1
> case base of
> "C" -> template' $ (TBase 'I') : ts
> "F" -> template' $ (TBase 'C') : ts
> "P" -> template' $ (TBase 'F') : ts
> "I" -> do base' <- popDNA 1
> case base' of
> "C" -> template' $ (TBase 'P'):ts
> "F" -> do l <- nat
> n <- nat
> template' ((NL n l):ts)
> "P" -> do l <- nat
> n <- nat
> template' ((NL n l):ts)
> "I" -> do base'' <- popDNA 1
> case base'' of
> "C" -> return ts
> "F" -> return ts
> "P" -> do n <- nat
> template' $ (N n):ts
> "I" -> do pushRNA =<< popDNA 7
> template' ts
> _ -> fail ""
> _ -> fail ""
> _ -> fail ""


This is where our error is. Are there any Haskell people who did this years ICFP contest who can tell us where we went wrong? Because I'm mystified, myself, and I really wish I had a working DNA -> RNA converter. In one of the examples, the "popDNA i" in the base case never seems to get called!


> matchreplace p t= matchreplace' p t 0 [] []
> matchreplace' [] t i e c = popDNA i >> (modify $ replace t e)
> matchreplace' (p:ps) t i e c = do
> (World _ dna) <- get
> case p of
> Base b -> if dna !!! i == (Just b)
> then matchreplace' ps t (i+1) e c
> else return ()
> Skip n -> if length dna > (i + n) then return ()
> else matchreplace' ps t (i+n) e c
> Search s -> case searchPost s dna i of
> Just n -> matchreplace' ps t n e c
> Nothing -> return ()
> GOpen -> matchreplace' ps t i e (i:c)
> GClose -> matchreplace' ps t i (e++[(subseq (head c) i dna)]) (subseq' 1 c)

> searchPost :: DNA -> DNA -> Int -> Maybe Int
> searchPost s dna i = let search n [] = Nothing
> search n (s':next) = if s' == s then Just n else search (n+1) next
> in liftM ((i+length s)+) $ search 0 ((map $ take (length s)) . tails $ genericDrop i dna)


> replace t e = replace' t e []

> replace' [] e r = (\(World rna dna) -> World rna (r++dna))
> replace' (t:ts) e r = case t of
> TBase b -> replace' ts e (r++[b])
> NL n l -> replace' ts e (r++(protect l $ fromMaybe [] (e!!!n)))
> N n -> replace' ts e (r++(asnat $ length $ fromMaybe [] (e!!!n)))


The rest of this are the utility functions used by the above. They're pretty simple, and should be familiar to you if you've done this year's ICFP competion


> asnat :: Integral n => n -> DNA
> asnat n | n==0 = "P"
> | n >= 0 && n `mod` 2==0 = 'I':(asnat $ n `div` 2)
> | n >= 0 = 'C' : (asnat $ n `div` 2)

> quote :: DNA -> DNA
> quote ('I':ds) = 'C':(quote ds)
> quote ('C':ds) = 'F':(quote ds)
> quote ('F':ds) = 'P':(quote ds)
> quote ('P':ds) = 'I':'C':(quote ds)
> quote _ = []

> protect :: Integral n => n -> DNA -> DNA
> protect 0 dna = dna
> protect n dna | n > 0 = protect (n-1) (quote dna)
> | otherwise = error "Protect should never receive a negative argument"


> nat :: (MonadState World m, Integral i) => m i
> nat = do dna <- popDNA 1
> case dna of
> "P" -> return 0
> "I" -> liftM (* 2) nat
> "F" -> liftM (* 2) nat
> "C" -> liftM (\x -> 2*x+1) nat
> _ -> fail ""

> consts :: MonadState World m => m DNA
> consts = do n <- popDNA 1
> case n of
> "C" -> liftM ('I':) consts
> "F" -> liftM ('C':) consts
> "P" -> liftM ('F':) consts
> "I" -> do n' <- peekDNA 1
> case n' of
> "C" -> popDNA 2 >> liftM ('P':) consts
> _ -> return ""
> _ -> return ""


And that's it for this file!

ICFP '07 Post-Mortem: III

Welcome to my series of posts on the ICFP competion entry I worked on!

"Testing" is our testing harness. the most exciting thing here is the function "test", which is just like the function "execute" in the Execute module, except it's wrapped around the IO monad and spits out diagnostics. If you're going to try an execute our code, you're going to want this.


===================
Testing.lhs


> module Testing where

> import Control.Monad.State
> import Maybe
> import Execute
> import System.IO
> import DNA


The strings iter1 through iter3 are the DNA sequences provided in the contest docs for testing out code.


> iter1 = "IIPIPICPIICICIIFICCIFPPIICCFPC"
> iter2 = "IIPIPICPIICICIIFICCIFCCCPPIICCFPC"
> iter3 = "IIPIPIICPIICIICCIICFCFC"


This is an all-in-one function to go from DNA to RNA, all while spitting out patterns and templates as debug messages.


> test :: DNA -> IO World
> test dna = flip execStateT (World [] dna) $ runMaybeT $
> let eval = do liftIO $ putStrLn "About to execute pattern"
> p <- liftM reverse pattern
> dna <- peekDNA 51
> liftIO $ do putStrLn $ "p: " ++ (show p)
> putStrLn $ "next dna: " ++ formatDNA dna
> putStrLn $ "About to execute template"
> t <- liftM reverse template
> dna <- peekDNA 51
> liftIO $ do putStrLn $ "t: " ++ (show t)
> putStrLn $ "next dna: " ++ formatDNA dna
> putStrLn $ "About to execute matchreplace"
> matchreplace p t
> dna <- peekDNA 51
> liftIO $ do putStrLn $ "next dna: " ++ formatDNA dna
> putStrLn $ "About to go through again!"
> eval
>
> in do liftIO $ putStrLn $ "Starting DNA: " ++ (formatDNA $ take 51 dna)
> eval

> formatDNA dna =
> if length dna > 50 then (take 50 dna) ++ "..." else dna

ICFP '07 Post-Mortem: II

Next up are some helper datatypes to make our code look more like the spec. If you're familiar with the contest (which is what I'm assuming) nothing here should look strange. For those of you that aren't familiar with the contest, here's the specification (PDF).


============
DNA.lhs


> module DNA where

> import Data.List

> type DNA = String
> type RNA = [DNA]

> subseq' a = genericDrop a

> subseq a b = genericTake (b-a) . genericDrop a

> (!!!) :: [a] -> Int -> Maybe a
> dna !!! x = if x >= length dna then Nothing else Just (dna !! x)

ICFP '07 Post-Mortem: I

This is the first of a few posts outlining Creighton and myself's effort towards this years IFCP programming competition. We didn't get too far, but I've learned a lot (more) about Haskell along the way.

I plan on doing one post per module, and this first post defines the Maybe monad transformer, which isn't in GHC (yet?) but made our code look much neater.


Check it out!

=======================
Maybe.lhs


> {-# OPTIONS -fallow-undecidable-instances -fglasgow-exts #-}

> module Maybe where


Almost all of this is taken from the Haskell Wiki


> import Control.Monad
> import Control.Monad.Trans
> import Control.Monad.State

> newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)}

> instance Functor m => Functor (MaybeT m) where
> fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x

> instance Monad m => Monad (MaybeT m) where
> return = MaybeT . return . return
> x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f)
> fail _ = MaybeT $ return Nothing

> instance Monad m => MonadPlus (MaybeT m) where
> mzero = MaybeT $ return mzero
> mplus x y = MaybeT $ liftM2 mplus (runMaybeT x) (runMaybeT y)

> instance MonadTrans MaybeT where
> lift = MaybeT . liftM return


Here are my contributions, which I shoudl proabbly give back to the wiki: the MonadIO instance and the MonadState instance. You'd think these would generalize to any instance of MonadTrans, seeing as I only use lift. I haven't tried it yet.


> instance MonadIO m => MonadIO (MaybeT m) where
> liftIO = lift . liftIO


My Haskell-fu isn't good enough to make the instance of MonadState work without -fallow-undecidable-instances. If anyone knows why, let me know.


> instance (MonadState s m) => MonadState s (MaybeT m) where
> get = lift get
> put = lift . put

Tuesday, July 10, 2007

Latex + Blogger help

I've been working on writing up my solutions to the exercises in Pierce's Basic Category Theory for Computer Scientists in this space, but I'm getting to the point where it's useful to include diagrams in my solutions.

Does anyone have any Linux-based workflows they'd like to share that could give a small JPEG if I supply a prelude and a LaTeX statement?

Listening:

Watching:

  • House
  • Ride Back