【问题标题】:How does the path function in Data.Graph work in Haskell?Data.Graph 中的 path 函数如何在 Haskell 中工作?
【发布时间】:2021-03-08 13:19:18
【问题描述】:

我已阅读有关路径函数的文档(对于有向图)。搜索引擎中没有太多内容。

我找到的所有内容基本上都归结为this link

它真正说的是路径函数的作用(我已经知道),以及输出示例。我想弄清楚的是路径功能如何工作或如何手动实现。到目前为止,我已经走到了这一步,但现在卡住了(或者可能完全走错了路,我不能确定):

member _ [] = False
member n (x:xs)
    | x == n = True
    | otherwise = membre n xs
    
getX :: (a, b) -> a
getX (x,_) = x

getY :: (a, b) -> b
getY (_,y) = y

getAllY :: [(a , b)] -> [b]
getAllY [] = [] 
getAllY (x:xs) = (getY x):(getAllY xs)

fltrX [] _ = []
fltrX (x:xs) n 
    | (getX x) == n = x:(fltrX xs n)
    | otherwise = fltrX xs n
    
fltrY [] _ = []
fltrY (x:xs) n 
    | (getY x) == n = x:(fltrY xs n)
    | otherwise = fltrY xs n

path' :: [(a , a)] -> a -> a -> Bool
path' [] _ _ = False
path' (xs) n m 
    | (member m (getAllY (fltrX xs n))) = True
    | otherwise = *recursive statement giving me a headache*

但我无法理解如何正确地进行递归。我想我只是盯着它太久了,不能再清楚地看到整个问题。逻辑应该是这样的:

  • 它从 x = n 的元组中获取 y 值
  • 它会在上面的 Y 值列表中找到所有 x 的元组
  • 如果没有 Y 值 = m,则对具有 n =(每个 X 值)且 m = m 的新元组列表执行路径函数
  • 如果在 Y 值中找到 m,则返回 true

谁能指出我正确的方向(双关语),最好不要为我输入代码?

谢谢!

【问题讨论】:

  • 你熟悉graph traversal这个概念吗?因为这就是 path 所做的(特别是深度优先搜索)。
  • 你看the actual implementation了吗?
  • @Li-yaoXia 这个概念我明白了,就是我的实现还没有搞好
  • @Bergi Cool,我一直在寻找类似的东西,但我想我错过了
  • @Bulbasaur 点击文档中的“来源”链接即可获得

标签: list haskell recursion graph functional-programming


【解决方案1】:

感谢评论者提供帮助我编写以下解决方案的资源:

member _ [] = False
member n (x:xs)
    | x == n = True
    | otherwise = member n xs
    
unique [] = []
unique (x:xs)
    | member x xs == True = unique xs
    | otherwise = x:(unique xs)


findAllEndsForX :: [(Int , Int)] -> Int -> [Int]
findAllEndsForX [] _ = []
findAllEndsForX ((a,b):xs) y
  | xs == [] = a:[b]
  | a == y = a:(findAllEndsForX xs b)
  | otherwise = (findAllEndsForX xs b)

accessible :: [(Int , Int)] -> Int -> [Int]
accessible [] _ = []
accessible xs n = unique (findAllEndsForX xs n)

path' :: [(Int , Int)] -> Int -> Int -> Bool
path' [] _ _ = False
path' xs v w = member w (accessible xs v)

我的最终目标是模仿路径功能的功能,而不一定是实现。我想在不使用任何预定义函数的情况下完成这项工作。

【讨论】:

  • 鼓舞人心的代码!而且读的很清楚,谢谢分享。不过有一个问题:我的印象是findAllEndsForX 的第一后卫不完整。我的意思是下面这行:| xs == [] = a:[b] 没有测试ya 还是b,这不可能成立。
猜你喜欢
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 2017-11-27
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多