【问题标题】:How to swap children in a tree in Haskell?如何在 Haskell 中交换树上的孩子?
【发布时间】:2020-05-19 20:13:03
【问题描述】:

我对 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

【问题讨论】:

    标签: haskell recursion tree


    【解决方案1】:

    你快到了,但你不会一路走下去。 swap 的第二行交换顶级树的 立即 子级(从 first secondsecond first),但如果 first 和/或 second 下有更多子级他们,这些孩子将保持不变,因为您没有以任何方式修改 firstsecond

    那么你如何交换firstsecond 的所有孩子,我想知道吗?好吧,它们都是Tree 类型......如果只有一个函数接受Tree,交换它的孩子,然后返回另一个Tree......哦,等等!这就是我们的swap 函数!我们为什么不用它来交换firstsecond 的所有孩子呢?

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

    【讨论】:

      猜你喜欢
      • 2016-07-05
      • 1970-01-01
      • 2014-09-03
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      相关资源
      最近更新 更多