Generics 具有唯一ID的Haskell泛型

Generics 具有唯一ID的Haskell泛型,generics,haskell,types,functional-programming,Generics,Haskell,Types,Functional Programming,我使用Uniplate已经有一段时间了,但是我发现缺乏识别节点的能力,这让我的工作更加困难。是否有允许绝对ID的泛型实现?下面是我希望此类实现具有的一些API的示例: universe :: (Data on) => on -> [(Id,on)] -- returns all sub nodes, with ids children :: (Data on) => on -> [(Id,on)] -- returns all direct children, with

我使用Uniplate已经有一段时间了,但是我发现缺乏识别节点的能力,这让我的工作更加困难。是否有允许绝对ID的泛型实现?下面是我希望此类实现具有的一些API的示例:

universe :: (Data on) => on -> [(Id,on)] -- returns all sub nodes, with ids
children :: (Data on) => on -> [(Id,on)] -- returns all direct children, with ids
transformAbove :: (Data on) => (on -> on) -> Id -> on -> on -- applies a transformation to all nodes which are ancestors of the node with the given id

这至少是前两个函数的部分解

{-# LANGUAGE GADTs #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

module Main where
import Text.Show.Pretty

import Data.Data
import Data.Generics.Uniplate.Data

type Id = [Int]

indexed :: Data on => on -> [(Int, on)]
indexed tree = zip [0..] $ children tree

labeled :: Data on => on -> [(Id, on)]
labeled tree = ([], tree) : [ (x:xs, tree) | (x, subtree) <- indexed tree, (xs, tree)
                                                          <- labeled subtree ]

universeI :: Data on => on -> [(Id, on)]
universeI = labeled

childrenI :: Data a => a -> [(Id, [a])]
childrenI = labeled . children
并获得以下标签:

[ ( [] , Fork (Fork (Leaf 1) (Leaf 2)) (Fork (Leaf 3) (Leaf 4)) )
, ( [ 0 ] , Fork (Leaf 1) (Leaf 2) )
, ( [ 0 , 0 ] , Leaf 1 )
, ( [ 0 , 1 ] , Leaf 2 )
, ( [ 1 ] , Fork (Leaf 3) (Leaf 4) )
, ( [ 1 , 0 ] , Leaf 3 )
, ( [ 1 , 1 ] , Leaf 4 )
]

好主意!我能给你的唯一帮助是查看
数据具体化
包,如果你想自己构建它。你希望
Id
的类型和值是什么?我希望
Id~[Int]
,不过如果我们事先知道d的最大分支B,我们还可以使用
Id~Int
并使每个子Id等于
parent Id*B+child index
ok,对于单个标量,最好使用整数覆盖Int,因为Id以指数形式增长到树深度。没有这类包吗?没有,这通常不是泛型库所能提供的,因为它只在树状结构中才有意义。如果需要此功能,可以在Uniplate或SYB上实现。
[ ( [] , Fork (Fork (Leaf 1) (Leaf 2)) (Fork (Leaf 3) (Leaf 4)) )
, ( [ 0 ] , Fork (Leaf 1) (Leaf 2) )
, ( [ 0 , 0 ] , Leaf 1 )
, ( [ 0 , 1 ] , Leaf 2 )
, ( [ 1 ] , Fork (Leaf 3) (Leaf 4) )
, ( [ 1 , 0 ] , Leaf 3 )
, ( [ 1 , 1 ] , Leaf 4 )
]