简体   繁体   English

Haskell - 玫瑰树路径

[英]Haskell - Rose Trees Paths

I'm doing a small project in Haskell and I'm having difficult in creating a function Paths of a "Rose Tree".我在 Haskell 做一个小项目,我很难创建“玫瑰树”的 function 路径。 My Rose Tree has a diferent point where I can have 4 possibilities since the beginning.我的玫瑰树有一个不同点,从一开始我就有4种可能性。

What I was trying to do was:我想做的是:

data RoseTree a = Start [RoseTree Movimento] | Node a [RoseTree Movimento]
        deriving (Eq, Show)

paths :: RoseTree Movimento -> [[Movimento]]
paths (Start []) = []
paths (Node n []) = [[n]]
paths (Node n ns) = map ((:) n . concat . paths) ns
paths (Start xs) = undefined

PS -> Tree Example: PS -> 树示例:

data Movimento = AndarEsquerda | AndarDireita | Trepar | InterageCaixa 
  deriving (Show, Read, Eq, Ord)

Start [Node AndarEsquerda [Node AndarDireita [Node AndarEsquerda [],Node Trepar []]],Node Trepar [Node AndarDireita [Node AndarDireita []],Node AndarEsquerda [Node AndarEsquerda []]]]

Tree Example树示例

In your code is an undefined right-hand side of expression paths (Start xs) .在您的代码中是表达式paths (Start xs)的未定义右侧。 It does not return the desired output if I defined using the expression (paths n) ++ (paths (Start ns)) .如果我使用表达式(paths n) ++ (paths (Start ns))定义,它不会返回所需的 output 。

Trivial cases [] are OK, but you do not go through the list with (n:ns) recursion to make the trivial ones occur.琐碎的情况 [] 是可以的,但是您不要通过带有(n:ns)递归的列表 go来使琐碎的事情发生。 You iterate using the map function, which is an alternative to recursion.您使用 map function 进行迭代,这是递归的替代方法。

I use the map function for scrolling to the width and recursion for browsing to the depth of the tree.我使用map function 滚动到树的宽度和递归浏览到树的深度。

paths2 :: RoseTree Movimento -> [[Movimento]]
paths2 (Start []) = []
paths2 (Node m []) = [[m]]
paths2 (Node m (n:ns)) = map ((++) [m]) ((paths2 n) ++ (paths2 (Start ns)))
paths2 (Start (n:ns)) = (paths2 n) ++ (paths2 (Start ns)) 

Output: Output:

[[AndarEsquerda,AndarDireita,AndarEsquerda],
[AndarEsquerda,AndarDireita,Trepar],
[Trepar,AndarDireita,AndarDireita],
[Trepar,AndarEsquerda,AndarEsquerda]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM