我的解释是,T 的导数(拉链)是所有实例的类型,类似于 T 的“形状”,但恰好有 1 个元素被“孔”替换。
例如,一个列表是
List t = 1 []
+ t [a]
+ t^2 [a,b]
+ t^3 [a,b,c]
+ t^4 [a,b,c,d]
+ ... [a,b,c,d,...]
如果我们用一个洞(表示为@)替换那些'a'、'b'、'c'等中的任何一个,我们将得到
List' t = 0 empty list doesn't have hole
+ 1 [@]
+ 2*t [@,b] or [a,@]
+ 3*t^2 [@,b,c] or [a,@,c] or [a,b,@]
+ 4*t^3 [@,b,c,d] or [a,@,c,d] or [a,b,@,d] or [a,b,c,@]
+ ...
另一个例子,二叉树是
data Tree t = TEmpty | TNode t (Tree t) (Tree t)
-- Tree t = 1 + t (Tree t)^2
所以添加一个洞会生成类型:
{-
Tree' t = 0 empty tree doesn't have hole
+ (Tree X)^2 the root is a hole, followed by 2 normal trees
+ t*(Tree' t)*(Tree t) the left tree has a hole, the right is normal
+ t*(Tree t)*(Tree' t) the left tree is normal, the right has a hole
@ or x or x
/ \ / \ / \
a b @? b a @?
/\ /\ / \ /\ /\ /\
c d e f @? @? e f c d @? @?
-}
data Tree' t = THit (Tree t) (Tree t)
| TLeft t (Tree' t) (Tree t)
| TRight t (Tree t) (Tree' t)
说明链式法则的第三个例子是玫瑰树(可变参数树):
data Rose t = RNode t [Rose t]
-- R t = t*List(R t)
导数是R' t = List(R t) + t * List'(R t) * R' t,意思是
{-
R' t = List (R t) the root is a hole
+ t we have a normal root node,
* List' (R t) and a list that has a hole,
* R' t and we put a holed rose tree at the list's hole
x
|
[a,b,c,...,p,@?,r,...]
|
[@?,...]
-}
data Rose' t = RHit [Rose t] | RChild t (List' (Rose t)) (Rose' t)
注意data List' t = LHit [t] | LTail t (List' t)。
(这些可能与拉链是“方向”列表的传统类型不同,但它们是同构的。)
导数是一种记录如何对结构中的位置进行编码的系统方法,例如我们可以搜索:(不是很优化)
locateL :: (t -> Bool) -> [t] -> Maybe (t, List' t)
locateL _ [] = Nothing
locateL f (x:xs) | f x = Just (x, LHit xs)
| otherwise = do
(el, ctx) <- locateL f xs
return (el, LTail x ctx)
locateR :: (t -> Bool) -> Rose t -> Maybe (t, Rose' t)
locateR f (RNode a child)
| f a = Just (a, RHit child)
| otherwise = do
(whichChild, listCtx) <- locateL (isJust . locateR f) child
(el, ctx) <- locateR f whichChild
return (el, RChild a listCtx ctx)
并使用上下文信息进行变异(插入漏洞):
updateL :: t -> List' t -> [t]
updateL x (LHit xs) = x:xs
updateL x (LTail a ctx) = a : updateL x ctx
updateR :: t -> Rose' t -> Rose t
updateR x (RHit child) = RNode x child
updateR x (RChild a listCtx ctx) = RNode a (updateL (updateR x ctx) listCtx)