通过给定的跟踪Hakell查找子树

时间:2019-10-21 02:17:49

标签: haskell

我对这个问题存有疑问。 问题是编写haskell函数跟踪(包括答案​​中的类型声明行),该跟踪 以Path p和BTree作为输入,通过跟踪路径返回您到达的子树 树。 请注意,(迹线p空)应始终返回空。 到目前为止,这是我的解决方案

username, joinDate, organization, friends, location.

然后我得到

data BTree a = Empty 
             | BNode a ( BTree a ) ( BTree a ) deriving (Show)
data Dir = Lft |Rght
type Path = [Dir]

tree = BNode 1 (  BNode 2 (BNode 4 (Empty) (Empty)) (BNode 5 (Empty) (Empty)) ) ( BNode 3 Empty Empty)

tree1 = BNode 1 (  BNode 2 (BNode 4 (Empty) (Empty)) (BNode 5 (Empty) (Empty)) ) (  BNode 2 (BNode 4 (Empty) (Empty)) (BNode 5 (BNode 3 Empty Empty) (Empty)) )

-- 1.
trace :: Path -> BTree a -> BTree a
trace  p Empty =  Empty 
trace [] a =  a 
trace  (x:xs) (BNode b left right) = if x == Lft then trace xs left else trace xs right

1 个答案:

答案 0 :(得分:5)

运算符==type class Eq的成员,因此,如果要在==类型上使用运算符Dir,则必须派生Eq为其输入类:

data Dir = Lft | Rght deriving Eq

但是,更好的方法是使用模式匹配而不是与==进行比较:

trace  p Empty =  Empty 
trace [] a =  a 
trace (Lft:xs) (BNode _ left _) = trace xs left 
trace (Rght:xs) (BNode _ _ right) = trace xs right