如何在哈斯克尔的树上交换孩子?



我对Haskell相当陌生。我想做的是交换树上孩子的顺序。如果两个孩子都是整数,我不确定如何让我的代码交换它们。谢谢!

# For example:
# If t1 = (* (+ 20 1) (- 10 8))
# Then when I call 'swap t1' I should get (* (- 8 10) (+ 1 20)) but I get (* (- 10 8) (+ 20 1))
#Here is my code:
data Tree =
TInt Integer
| TOp String Tree Tree
t1 = TOp "*" (TOp "+" (TInt 20) (TInt 1))
(TOp "-" (TInt 10) (TInt 8))
swap :: Tree -> Tree
swap (TInt i) = TInt i
swap (TOp s first second) = TOp s second first

你快到了,但你不会一路走下去。swap的第二行交换顶级树的直接子级(从first secondsecond first(,但如果first和/或second下还有其他子级,则这些子级将保持不交换状态,因为您不会以任何方式修改firstsecond

那么,我想知道firstsecond的所有孩子如何交换呢?好吧,他们都是Tree型...如果有一个函数可以接受Tree,交换其子项并返回另一个Tree......哦,等等!这就是我们的swap功能!我们为什么不用它来交换firstsecond的所有孩子呢?

swap (TOp s first second) = TOp s (swap second) (swap first)

最新更新