如何在Haskell中压缩玫瑰树

0 tree haskell functional-programming

对于Haskell Tic Tac Toe游戏,我试图压缩两棵玫瑰树.我把玫瑰树定义为

data Rose a = a :> [Rose a]
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

zipTrees :: Rose Board -> Rose Int -> Rose (Board, Int)
zipTrees (b :> []) (i :> []) = (b,i) :> []
zipTrees (b :> chib) (i :> chii) = (b, i) :> zipTrees chib chii
Run Code Online (Sandbox Code Playgroud)

但出现错误,因为它可能不符合预期的类型Rose Int,并Rose Board[Rose Int][Rose Board]分别.我对如何以任何其他方式压缩树木一无所知.

为了进一步说明,如果我想拉树

a :> [a :> [a :> []], a :> []]
Run Code Online (Sandbox Code Playgroud)

而且b :> [b :> [b :> []], b :> []],我想要归还树

(a, b) :> [(a, b) :> [(a, b) :> []], (a,b) :> []]
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

chib并且chii是树木的列表,而不是树木本身.你不能只是打电话zipTrees给他们.你需要递减

zipTrees :: Rose Board -> Rose Int -> Rose (Board, Int)
zipTrees (b :> [])       (i :> _)        = …
zipTrees (b :> _)        (i :> [])       = …
zipTrees (b :> (cb:cbs)) (i :> (ci:cis)) = …
Run Code Online (Sandbox Code Playgroud)

或者只是使用 zipWith

zipTrees :: Rose Board -> Rose Int -> Rose (Board, Int)
zipTrees (b :> chib) (i :> chii) = (b, i) :> zipWith zipTrees chib chii
--                                           ^^^^^^^
Run Code Online (Sandbox Code Playgroud)