这是 Haskell 中的一个示例,其中包含真正的慢速巴士,构建从目的地到起点的路线:
import Data.List (elemIndex)
import Data.Maybe (fromJust)
cities = ["New York", "Philadelphia", "Washington", "Buffalo"]
buses = [([0,1],2), ([0,2],1), ([1,2],1), ([2,3],4)] --buses (cities a1 b1 as indexes, num days of travel)
solve origin destination maxDays = do
lastBus <- filter ((== fromJust (elemIndex destination cities)) . last . fst) buses
solve' [lastBus] where
solve' result
| sum (map snd result) > maxDays = []
| cities !! (head . fst . head $ result) == origin =
[(map (map (cities !!) . fst) result, show (sum . map snd $ result) ++ " Days Travel")]
| otherwise =
let potentialBuses = filter ((== (head . fst . head $ result)) . last . fst) buses
in if null potentialBuses
then []
else do
bus <- potentialBuses
solve' (bus:result)
OUTPUT:
*Main> solve "New York" "Buffalo" 6
[([["New York","Washington"],["Washington","Buffalo"]],"5 Days Travel")]
*Main> solve "New York" "Buffalo" 3
[] --trip longer than D
*Main> solve "New York" "Washington" 3
[([["New York","Washington"]],"1 Days Travel"),
([["New York","Philadelphia"],["Philadelphia","Washington"]],"3 Days Travel")]