Haskell 如何获取从根到所需节点的路径,即包括第一个数字作为rooth,然后是child->;儿童->;直到孩子的父母
如果请求9,则应返回(True,[1,3])(如果退出) 如果不存在,则应返回(False,[])Haskell 如何获取从根到所需节点的路径,即包括第一个数字作为rooth,然后是child->;儿童->;直到孩子的父母,haskell,tree,Haskell,Tree,如果请求9,则应返回(True,[1,3])(如果退出) 如果不存在,则应返回(False,[]) 首先,为什么给定树中9的路径等于[1,3]?如果不是[1,1]-从1到3沿着第一个分支向下走,然后再从3到9沿着第一个分支向下走 其次,任何树中的任何元素都可能出现0次或更多次-因此,函数应该返回一个路径列表(其中包含某些类型的0次或更多次出现)。您不需要额外的布尔值-要检查是否没有路径,请检查列表是否为null data Tree = Tree Int [Tree] deriving (Sho
首先,为什么给定树中9的路径等于[1,3]?如果不是[1,1]-从1到3沿着第一个分支向下走,然后再从3到9沿着第一个分支向下走 其次,任何树中的任何元素都可能出现0次或更多次-因此,函数应该返回一个路径列表(其中包含某些类型的0次或更多次出现)。您不需要额外的布尔值-要检查是否没有路径,请检查列表是否为
null
data Tree = Tree Int [Tree] deriving (Show , Eq)
isPrsnt num (Tree nnum ls:xs) parents | (nnum==num) = (True,parents)
| (fst (isPrsnt num( ls ) (parents ++[nnum])) == False) = isPrsnt nnum xs (init parents)
| otherwise = isPrsnt nnum xs parents
isPrsnt num ([]) parents = (False,parents)
在正确的类型下,函数本身非常简单:
type Path = [Int]
paths :: Eq a => a -> Tree a -> [Path]
这些类型并不完全匹配。您的描述说明
([Int],Bool)
,您的代码(Bool[Int])
。为什么不使用Maybe[Int]
?使用Maybe
而不是元组。顺便说一下,t1
甚至不包含7
或9
。
type Path = [Int]
paths :: Eq a => a -> Tree a -> [Path]
paths a = go where
go (Tree b ts) =
[ [] | a == b ] ++
concat [ map (i:) (go t) | (i,t) <- zip [0..] ts ]
member :: Eq a => a -> Tree a -> Bool
member a t = not $ null $ paths a t