【算法】算法图解笔记_广度优先搜索 -Haskell代码实现

以前的广度优先遍历没有Haskell代码的实现,这里补上。下面代码使用了unordered-containers包的哈希表,用来实现图;containers包的Seq类型,用来实现队列,主要是由于使用内置的列表类型效率太差。数据结构

module Main where

import qualified Data.HashMap.Strict as HM
import           Data.Maybe (fromJust)
import qualified Data.Sequence       as DS

graph :: HM.HashMap String [String]
graph = HM.fromList [("you",["alice", "bob", "claire"]),
                    ("bob", ["anuj", "peggy"]),
                    ("alice", ["peggy"]),
                    ("claire", ["thom", "jonny"]),
                    ("anuj",[]),
                    ("peggy",[]),
                    ("thom",[]),
                    ("jonny",[])
                   ]

personIsSeller :: String -> Bool
personIsSeller name = last name == 'm'

search :: HM.HashMap String [String] -> String -> Bool
search graph name = loop $ DS.fromList (graph HM.! name)
  where loop queue
          | null queue = False
          | personIsSeller h = True
          | otherwise = loop $ (DS.drop 1 queue) DS.>< DS.fromList (graph HM.! h)
          where h = queue `DS.index` 0

main :: IO ()
main = do
  print $ search graph "you"

为了能与Python对照,总体风格上与Python代码保持一致,包括测试用例、图的实现方式等等。
Haskell标准模块并不包含一些经常使用的数据类型,因此,平常开发中须要大量使用其余三方的包,其中containers和unordered-containers是最经常使用的容器包。oop

containers包含经常使用的图、树、集合等结构,具体包含Data.Graph、Data.Tree、Data.Map、Data.IntMap、Data.Set、Data.IntSet、以及例子中使用到的Data.Sequence等。测试

正如名字所示,unordered-containers包实现了基于无序的数据结构,包含基于哈希的映射和集合。spa

请继续关注个人公众号文章
图片描述code

相关文章
相关标签/搜索