3

我对编写递归代码的高阶方式(递归方案)感兴趣,其中递归调用之间可能存在依赖关系。

作为一个简化的例子,考虑一个遍历整数树的函数,检查总和是否小于某个值。我们可以对整棵树求和,并将其与最大值进行比较。或者,我们可以在超过最大值后立即保持运行总和并短路:

data Tree = Leaf Nat | Node Tree Tree

sumLT :: Nat -> Tree -> Bool
sumLT max t = sumLT' max t > 0

sumLT' :: Nat -> Tree -> Int
sumLT' max (Leaf n) = max - n
sumLT' max (Node l r) = 
  let max' = sumLT' max l
   in if max' > 0 then sumLT' max' r else 0

有没有办法用递归方案来表达这个想法——本质上是一个有序的遍历?我对尽可能一般地编写这样的有序遍历感兴趣。

理想情况下,我想要某种方式来编写遍历,其中在数据结构上折叠(或展开)的函数决定了遍历的顺序。无论我最终得到什么抽象,我都希望能够编写sumLT'上面遍历的逆序版本,而不是从右到左:

sumLT'' :: Nat -> Tree -> Int
sumLT'' max (Leaf n) = max - n
sumLT'' max (Node l r) = 
  let max' = sumLT'' max r
   in if max' > 0 then sumLT'' max' l else 0
4

2 回答 2

3

像往常一样,折叠成 endofunctions 为您提供了处理顺序/状态传递的概念:

import Numeric.Natural

data Tree = Leaf Natural | Node Tree Tree

cata :: (Natural -> r) -> (r -> r -> r) -> Tree -> r
cata l n (Leaf a)     = l a
cata l n (Node lt rt) = n (cata l n lt) (cata l n rt)

sumLT :: Natural -> Tree -> Bool
sumLT max t = cata (\ a max -> max - a)     -- left-to-right
                   (\ l r max -> let max' = l max in
                        if max' > 0 then r max' else 0)
                   t max > 0

sumLT' :: Natural -> Tree -> Bool
sumLT' max t = cata (\ a max -> max - a)     -- right-to-left
                    (\ l r max -> let max' = r max in
                         if max' > 0 then l max' else 0)
                    t max > 0

尝试一下:

> sumLT 11 (Node (Leaf 10) (Leaf 0))
True

> sumLT 11 (Node (Leaf 10) (Leaf 1))
False

> sumLT 11 (Node (Leaf 10) (Leaf undefined))
*** Exception: Prelude.undefined

> sumLT 11 (Node (Leaf 11) (Leaf undefined))
False

> sumLT 11 (Node (Leaf 10) (Node (Leaf 1) (Leaf undefined)))
False

> sumLT' 11 (Node (Leaf undefined) (Leaf 11))
False

与往常一样,Haskell 的惰性提供了提前短路/退出的能力。从示例中可以看出,如果cata's第二个参数(节点折叠函数)不需要其参数之一的值,则根本不会实际访问相应的分支。

于 2021-01-30T14:43:10.023 回答
0

我会利用 Haskell 的懒惰作为我的优势。将树变成列表(这是一种变态),创建部分和,并找到大于限制的第一个。

{-# language DeriveFoldable #-}

module ShortSum where
import Data.Foldable
  
data Tree a = Leaf a | Node (Tree a) (Tree a)
  deriving Foldable

type Nat   = Int
type TreeN = Tree Nat

sumLt :: Nat -> TreeN -> Bool
sumLt mx = any (> mx) . scanl1 (+) . toList
于 2021-01-30T18:25:06.237 回答