简体   繁体   中英

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". My Rose Tree has a diferent point where I can have 4 possibilities since the beginning.

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:

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) . It does not return the desired output if I defined using the expression (paths n) ++ (paths (Start ns)) .

Trivial cases [] are OK, but you do not go through the list with (n:ns) recursion to make the trivial ones occur. You iterate using the map function, which is an alternative to recursion.

I use the map function for scrolling to the width and recursion for browsing to the depth of the tree.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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