Permalink
Browse files

Adding BFS algorithms from ai-class

  • Loading branch information...
roman committed Oct 15, 2011
0 parents commit efa57ee54afc5aa00666aec48b34c1846ee6fbff
Showing with 376 additions and 0 deletions.
  1. +3 −0 .gitignore
  2. +8 −0 LICENSE
  3. +6 −0 README.md
  4. +2 −0 Setup.hs
  5. +81 −0 ai-class-haskell.cabal
  6. +37 −0 src/Lesson2/BFS.hs
  7. +64 −0 src/Lesson2/BFS/Enumerator.hs
  8. +38 −0 src/Lesson2/BFS/Parser.hs
  9. +95 −0 src/Lesson2/BFS/Types.hs
  10. +24 −0 src/Lesson2/Input.txt
  11. +12 −0 src/Lesson2/Types.hs
  12. +6 −0 src/Main.hs
@@ -0,0 +1,3 @@
+cabal-dev/*
+dist/*
+*.swp
@@ -0,0 +1,8 @@
+Copyright (c) 2011 Roman Gonzalez
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
@@ -0,0 +1,6 @@
+[ai-class.com](http://www.ai-class.com) Stanford's algorithms in Haskell
+
+This project was developed for the sole purpose of helping myself understand
+better the concept and algorithms in the ai-class online course.
+
+Author: [@romanandreg](http://twitter.com/romanandreg)
@@ -0,0 +1,2 @@
+import Distribution.Simple
+main = defaultMain
@@ -0,0 +1,81 @@
+-- aiclass.cabal auto-generated by cabal init. For additional options,
+-- see
+-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.
+-- The name of the package.
+Name: ai-class-haskell
+
+-- The package version. See the Haskell package versioning policy
+-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for
+-- standards guiding when and how versions should be incremented.
+Version: 0.1
+
+-- A short (one-line) description of the package.
+Synopsis: Algorithms given in the Stanford's ai-class done in Haskell
+
+-- A longer description of the package.
+-- Description:
+
+-- The license under which the package is released.
+License: MIT
+
+-- The file containing the license text.
+License-file: LICENSE
+
+-- The package author(s).
+Author: Roman Gonzalez
+
+-- An email address to which users can send suggestions, bug reports,
+-- and patches.
+Maintainer: romanandreg@gmail.com
+
+-- A copyright notice.
+-- Copyright:
+
+Category: Academic
+
+Build-type: Simple
+
+-- Extra files to be distributed with the package, such as examples or
+-- a README.
+-- Extra-source-files:
+
+-- Constraint on the version of Cabal needed to build this package.
+Cabal-version: >=1.2
+
+Executable ai-class-haskell
+
+ hs-source-dirs: src
+ main-is: Main.hs
+ Build-depends:
+ attoparsec,
+ attoparsec-enumerator,
+ base,
+ bytestring,
+ containers,
+ data-lens,
+ data-lens-template,
+ directory,
+ enumerator,
+ hashable,
+ mtl,
+ utf8-string
+
+Library
+ -- Modules exported by the library.
+ hs-source-dirs: src
+ Exposed-modules:
+ Lesson2.Types,
+ Lesson2.BFS,
+ Lesson2.BFS.Enumerator,
+ Lesson2.BFS.Parser,
+ Lesson2.BFS.Types
+
+ -- Packages needed in order to build this package.
+ -- Build-depends:
+
+ -- Modules not exported by this package.
+ -- Other-modules:
+
+ -- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.
+ -- Build-tools:
+
@@ -0,0 +1,37 @@
+module Lesson2.BFS
+ (
+ BasicNode(..)
+ , BasicEdge(..)
+ , BasicGraph(..)
+ , basicGraphEdges
+ , basicGraphNodes
+ , enumBFS
+ , consumeTillNode
+ , parseGraph
+ , main
+ ) where
+
+import Control.Monad (mapM_)
+import Data.Attoparsec.Enumerator (iterParser)
+import Data.Enumerator (run_, ($$))
+import Data.Enumerator.Binary (enumFile)
+
+import Lesson2.Types
+import Lesson2.BFS.Enumerator
+import Lesson2.BFS.Types
+import Lesson2.BFS.Parser
+
+main :: IO ()
+main = do
+ -- Parse the graph from Input.txt
+ graph <- run_ $
+ enumFile "src/Lesson2/Input.txt" $$ iterParser parseGraph
+ -- Set the initial State
+ let startNode = BasicNode (City "Arad")
+ -- Set the goal State
+ let goalNode = BasicNode (City "Bucharest")
+ -- Run basic BFS
+ result <- run_ $ enumBFS startNode graph $$ consumeTillNode goalNode
+ -- Print visit order
+ mapM_ print result
+
@@ -0,0 +1,64 @@
+module Lesson2.BFS.Enumerator where
+
+import Control.Monad.Trans (MonadIO, liftIO)
+import Data.Enumerator (
+ Stream(..)
+ , Step(..)
+ , Iteratee(..)
+ , Enumerator
+ , (>>==)
+ , returnI
+ , continue
+ , yield
+ )
+import Data.Hashable (Hashable(..))
+import Data.Ord (Ord(..), comparing)
+
+import qualified Data.Set as Set
+
+import Lesson2.BFS.Types
+
+-------------------------------------------------------------------------------
+
+newtype FrontierEntry a
+ = FE { fromFE :: (Int, BasicNode a) }
+ deriving (Show, Eq, Ord)
+
+-------------------------------------------------------------------------------
+
+enumBFS :: (MonadIO m, Show a, Hashable a)
+ => BasicNode a
+ -> BasicGraph a
+ -> Enumerator (BasicNode a) m b
+enumBFS source0 g =
+ go Set.empty (Set.singleton $ FE (0, source0))
+ where
+ go _ _ step@(Yield {}) = returnI step
+ go explored0 frontier0 step@(Continue consumer) = Iteratee $
+ case Set.minView frontier0 of
+ Just (FE (i, source), frontier1) -> do
+ let explored = Set.insert source explored0
+ let frontier = Set.union frontier1 .
+ Set.fromList .
+ Prelude.map (\n -> FE (i + 1, n)) .
+ Prelude.filter (`Set.notMember` explored) $
+ getNodeNeighbours source g
+ runIteratee $ consumer (Chunks [source]) >>== go explored frontier
+ Nothing -> return step
+
+-------------------------------------------------------------------------------
+
+consumeTillNode :: (Monad m, Hashable a)
+ => BasicNode a
+ -> Iteratee (BasicNode a) m [BasicNode a]
+consumeTillNode dest = continue $ go []
+ where
+ go acc EOF = yield [] EOF
+ go acc (Chunks ns) = Iteratee $ do
+ let (as, bs) = span (dest /=) ns
+ case bs of
+ [] -> return $ Continue $ go $ acc ++ as
+ (x:xs) -> return $ Yield (acc ++ as ++ [x]) (Chunks xs)
+
+-------------------------------------------------------------------------------
+
@@ -0,0 +1,38 @@
+module Lesson2.BFS.Parser where
+
+import Control.Applicative ((<$>), (<*>), (<*), (*>))
+import Data.Attoparsec.Char8
+import Data.ByteString.UTF8 (toString)
+import Data.Monoid (mconcat)
+
+import Lesson2.Types
+import Lesson2.BFS.Types
+
+tillComma = takeTill (== ',')
+tillEOL = takeTill (== '\n')
+comma = char ','
+eol = char '\n'
+
+parseCity =
+ entry <$> (skipSpace *>
+ tillComma <*
+ comma)
+ where
+ entry = BasicNode . City . toString
+
+parseEntry :: Parser (BasicGraph City)
+parseEntry = do
+ a <- parseCity
+ b <- parseCity
+ tillEOL
+ eol
+ return $ createGraph a b
+ where
+ createGraph a b =
+ appendEdge a b .
+ appendNode a $
+ appendNode b emptyGraph
+
+parseGraph :: Parser (BasicGraph City)
+parseGraph = mconcat <$> many1 parseEntry
+
@@ -0,0 +1,95 @@
+{-# LANGUAGE TemplateHaskell #-}
+module Lesson2.BFS.Types where
+
+import Data.Lens.Common (getL, modL)
+import Data.Lens.Template (makeLenses)
+import Data.List (foldl', sort)
+import Data.Hashable (Hashable(..))
+import Data.Monoid (Monoid(..))
+import Data.Ord (Ord(..), comparing)
+import Data.Set (Set)
+import qualified Data.Set as Set
+
+-------------------------------------------------------------------------------
+
+data BasicGraph a
+ = BasicGraph {
+ _basicGraphNodes :: Set (BasicNode a)
+ , _basicGraphEdges :: Set (BasicEdge a)
+ }
+
+data BasicNode a
+ = BasicNode {
+ basicNodeValue :: a
+ }
+
+data BasicEdge a
+ = BasicEdge {
+ basicEdgeSource :: BasicNode a
+ , basicEdgeSink :: BasicNode a
+ }
+
+makeLenses [''BasicGraph]
+
+-------------------------------------------------------------------------------
+
+instance Show a => Show (BasicNode a) where
+ show (BasicNode v) = show v
+
+instance Show a => Show (BasicEdge a) where
+ show (BasicEdge a b) = "(" ++ show a ++ ", " ++ show b ++ ")"
+
+instance Hashable a => Monoid (BasicGraph a) where
+ mempty = emptyGraph
+ mappend (BasicGraph n0 e0) (BasicGraph n1 e1) =
+ BasicGraph (n0 `mappend` n1)
+ (e0 `mappend` e1)
+
+
+instance Hashable a => Hashable (BasicNode a) where
+ hash (BasicNode a) = 0 `hashWithSalt` a
+
+instance Hashable a => Hashable (BasicEdge a) where
+ hash (BasicEdge a b) = foldl' hashWithSalt 1 [a, b]
+
+instance Hashable a => Eq (BasicNode a) where
+ a == b = hash a == hash b
+
+instance (Hashable a) => Ord (BasicNode a) where
+ compare = comparing hash
+
+instance Hashable a => Eq (BasicEdge a) where
+ a == b = hash a == hash b
+
+instance Hashable a => Ord (BasicEdge a) where
+ compare = comparing hash
+
+-------------------------------------------------------------------------------
+
+emptyGraph :: BasicGraph a
+emptyGraph = BasicGraph Set.empty Set.empty
+
+appendNode :: Hashable a => BasicNode a -> BasicGraph a -> BasicGraph a
+appendNode node = modL basicGraphNodes (Set.insert node)
+
+appendEdge :: Hashable a
+ => BasicNode a
+ -> BasicNode a
+ -> BasicGraph a
+ -> BasicGraph a
+appendEdge a b = modL basicGraphEdges (Set.union otherSet)
+ where
+ otherSet = Set.fromList [BasicEdge a b, BasicEdge b a]
+
+-------------------------------------------------------------------------------
+
+getNodeNeighbours :: Hashable a => BasicNode a -> BasicGraph a -> [BasicNode a]
+getNodeNeighbours n =
+ Set.fold getOtherNode [] .
+ getL basicGraphEdges
+ where
+ getOtherNode e acc
+ | basicEdgeSource e == n = basicEdgeSink e : acc
+ | otherwise = acc
+
+
@@ -0,0 +1,24 @@
+Arad, Zerind, 75
+Arad, Sibiu, 140
+Arad, Timisoara, 111
+Zerind, Oradea, 71
+Timisoara, Lugoj, 111
+Oradea, Sibiu, 151
+Lugoj, Mehadia, 70
+Mehadia, Drobatea, 75
+Drobatea, Craiova, 120
+Craiova, Rimnicu Vilcea, 146
+Craiova, Pitesti, 138
+Sibiu, Rimnicu Vilcea, 80
+Sibiu, Fagaras, 99
+Fagaras, Bucharest, 211
+Rimnicu Vilcea, Pitesti, 97
+Pitesti, Bucharest, 101
+Bucharest, Giurgiu, 90
+Bucharest, Urziceni, 85
+Urziceni, Vaslui, 142
+Urizceni, Hirsova, 98
+Vaslui, Iasi, 92
+Iasi, Neamt, 87
+Hirsova, Efoire, 86
+
@@ -0,0 +1,12 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+module Lesson2.Types where
+
+import Data.Hashable (Hashable(..))
+
+newtype City
+ = City { getCityName :: String }
+ deriving (Eq, Ord, Hashable)
+
+instance Show City where
+ show = show . getCityName
+
@@ -0,0 +1,6 @@
+module Main where
+
+import qualified Lesson2.BFS
+
+main :: IO ()
+main = Lesson2.BFS.main

0 comments on commit efa57ee

Please sign in to comment.