haskell - uniplate 的 `universeBi` 可以用于以广度优先方式检索节点吗?
问题描述
是否可以使用 UniplateuniverseBi
获得广度优先的输出?结果似乎以深度优先的方式返回。我想知道如何使用 uniplate 以universeBi
广度优先的方式检索。
为了说明,请考虑以下玩具程序:
{-# LANGUAGE DeriveDataTypeable #-}
import Data.Data
import Data.Generics.Uniplate.Data
data A = A B Int deriving (Data, Typeable)
data B = B Int deriving (Data, Typeable)
val :: A
val = A (B 1) 2
ints :: [Int]
ints = universeBi val
我得到:
*Main> ints
[1,2]
但这是深度优先的,正如1
从B
节点获得的那样。我宁愿以广度优先的顺序得到它,即接收[2,1]
。这在单板中可以实现吗?
解决方案
您可以深入研究Str
返回的结构biplate
:
layers :: Str a -> [[a]]
layers Zero = []
layers (One x) = [[x]]
layers (Two f x) = catLayers (layers f) ([] : layers x)
where catLayers [] ys = ys
catLayers xs [] = xs
catLayers (x : xs) (y : ys) = (x ++ y) : catLayers xs ys
layersBi :: Biplate from to => from -> [[to]]
layersBi = layers . fst . biplate
breadthBi :: Biplate from to => from -> [to]
breadthBi = concat . layersBi
所以现在
breadthBi (A (B 1) 2) :: [Int]
-- = [2, 1]
和
data Tree a = Branch (Tree a) a (Tree a) | Leaf deriving (Data, Typeable)
-- 4
-- 2 6
-- 1 3 5 7
example = Branch (Branch (Branch Leaf 1 Leaf) 2 (Branch Leaf 3 Leaf)) 4 (Branch (Branch Leaf 5 Leaf) 6 (Branch Leaf 7 Leaf))
(layersBi :: Data a => Tree a -> [[a]]) example
-- = [[],[4],[2,6],[1,3,5,7]]
我不确定它是否真的能保证Str
准确地反映数据类型的结构,但它似乎可以。如果必须的话,您可以改为从原语中烹制一些东西Data
。
推荐阅读
- objective-c - 将 Objective-C 类存储在数组中并使用它们
- python - 如何根据 id 和 value 将序列号放入我的重复值中
- jquery - jquery.contextMenu ajax提交后无法读取属性
- graphql - 在graphql.js中调用graphql方法的requestString参数是什么?
- sparql - 如何“旋转” SPARQL 导致“循环”?
- simulation - Anylogic变量未更新
- css - jQuery UI 可排序:防止在全高列之间使用连接列表进行水平滚动
- python - 根据另一个列表中的属性对对象列表进行排序
- c# - 如何创建包含两个 DateTime 对象之间的日期的字符串数组或列表?
- android - 为什么 Android 上的阴影会被其他组件覆盖?