读FingerTree论文,记笔记 (上)

所有权利归论文原作者所有,如果侵权,本人将立刻删除这篇文章。

本文中的代码可以在这里找到https://github.com/hgztheyoung/CopiedCodes/blob/master/ft.hs
论文中的实现见 http://hackage.haskell.org/package/fingertree
这篇博客里的图不错,值得参考
http://www.dalnefre.com/wp/2011/09/finger-tree-a-functional-value-object/

看了[1]里的答案,知道了FingerTree这么个数据结构,十分好奇。
于是从这里[2]找了篇论文,抄抄代码,写写笔记

2 Preliminaries

2.1 Monoid

class Monoid a where
  mempty  :: a
  mappend :: a->a->a

A type with an associative operation and an identity forms a monoid.
具有一个可结合运算和单位元的类型构成一个Monoid[3]

 可结合  
    (A `mappend` B) `mappend` C = A `mappend` (B `mappend` C)
 单位元  
    A `mappend` mempty = A
    mempty `mappend` A  = A

具有矩阵乘法和单位矩阵的n*n矩阵构成一个Monoid
具有字符串连接和空字符串的字符串构成一个Monoid

2.2 Right and left reductions

A reduction with a monoid yields the same result
however we nest the applications of mappend, but for a reduction with an arbitrary
constant and binary operation we must specify a particular nesting.

对monoid做reduction,无论运算顺序如何,总会得到相同的结果 (因为monoid满足结合律)
而对于任意的常量和二元运算做reduction,我们必须指定一种特定的运算顺序(foldr和foldl的区别)

class Reduce f where
  reducer :: (a -> b -> b) -> (f a -> b -> b)
  reducel :: (b -> a -> b) -> (b -> f a -> b)

这个reducer就是说,输入一个 (a->b->b)的二元运算,就能输出一个(f a->b->b)的函数 (柯里化了,变成这种形式)
可以把这里的f理解成某种泛型的容器,比如list。f a->b->b就是说,给个a类型的容器,比如a的列表,a类型的树等等。
给个b类型的初始值,一般是mempty。就能遍历整个容器,最终得到一个b类型的结果

toList :: (Reduce f) => f a -> [a]
toList s = consbar s [] where
  consbar = reducer (:)

toList的签名是说,只要f是实现了Reduce的容器,就能从f a类型得到a类型的列表
(:)是 a->[a]->[a]类型,所以 reducer (:)是 f a->[a]->[a]类型。

3 Simple sequences

As a starting point, consider ordinary 2-3 trees, like the one
below:

raw_2-3_tree.PNG

只在最后一层存放数据

Operations on such trees typically take time logarithmic in the size of the tree,
but for a sequence implementation we would like to add and remove elements from
either end in constant time.

想要实现O(1)的在两端增加和删除元素,怎么办呢?现在是O(logN)

3.1 Finger Tree

A structure providing efficient access to nodes of a tree near a distinguished location
is called a finger.To provide efficient access to the ends of a sequence, we wish to place fingers at
the left and right ends of this tree. Imagine taking hold of the end nodes of the
example tree above and lifting them up together.

为了高效的访问两端,把树往中间对折。原来的左右两端成为根,原来的根成为最中间最下方的节点

ft-step1.PNG
ft-step2.PNG
ft-step3.png

这里[4]有更多例子。

注意到原来在底端的最左边和最右边,现在在顶端,可以快速访问到。
且越是原来靠近边缘的节点,现在就越接近顶端。在中间的节点可能访问代价会变大。
不过没关系,最多变大一倍,还是O(logN)复杂度。

而且finger tree每向下一层,节点就变得更大。

定义

data FingerTree a = Empty
  | Single a
  | Deep (Digit a) (FingerTree (Node a)) (Digit a)

type Digit a = [a]
data Node a = Node2 a a | Node3 a a a

Before moving on, we instantiate the generic definition of reduction to these
types. Reduction of nodes is trivial:

instance Reduce Node where
  reducer (-<) (Node2 a b) z = a -< (b -< z)
  reducer (-<) (Node3 a b c) z = a -< (b -< (c -< z))
  reducel (>-) z (Node2 b a) = (z >- b) >- a
  reducel (>-) z (Node3 c b a) = ((z >- c) >- b) >- a

Reduction of finger trees uses single and double liftings of the binary operation:

instance Reduce FingerTree where
  reducer _ Empty z = z
  reducer (-<) (Single x) z = x -< z
  reducer (-<) (Deep pr m sf ) z = pr -<< (m -<<< (sf -<< z))
    where (-<<) = reducer (-<)
          (-<<<) = reducer (reducer (-<))
  reducel _ z Empty = z
  reducel (>-) z (Single x) = z >- x
  reducel (>-) z (Deep pr m sf ) = ((z >>- pr) >>>- m) >>- sf
    where (>>-) = reducel (>-)
          (>>>-) = reducel (reducel (>-))

-<,-<<,-<<<,只是一些函数名而已。
在这段里头,-<<是 [a]->b->b类型, -<<<是(FingerTree (Node a))->b->b类型

这块是我瞎猜的

-< :: a -> b -> b

reducer :: (a -> b -> b) -> (f a -> b -> b)

reducer (-<) f0 a -> b -> b

reducer (reducer (-<))  (f1 (f0 a)) -> b -> b

然后f0匹配到Node,f1匹配到FingerTree。所以-<<<就能处理FingerTree(Node a)类型了
当然前提是FingerTree和Node都instance了Reduce。

试一下是不是真的能Reduce

*Main> toList Empty
[]
*Main> toList (Single 1)
[1]
*Main> toList (Deep [1,2] Empty [3,4])
[1,2,3,4]
*Main> toList (Deep [1,2] (Single (Node3 3 4 5)) [6,7])
[1,2,3,4,5,6,7]

3.2 Deque operations

入队

infixr 5 <|
(<|) :: a -> FingerTree a -> FingerTree a
a <| Empty = Single a
a <| Single b = Deep [a] Empty [b]
a <| Deep [b,c,d,e] m sf = Deep [a,b] (Node3 c d e <| m) sf
a <| Deep pr m sf = Deep ([a] ++ pr) m sf

infixl 5 |>
(|>)  :: FingerTree a -> a -> FingerTree a
Empty               |> a = Single a
Single b            |> a = Deep [b] Empty [a]
Deep pr m [e,d,c,b] |> a = Deep pr (m |> Node3 e d c) [b,a]
Deep pr m sf        |> a = Deep pr m (sf ++ [a])

(<||) :: (Reduce f) => f a -> FingerTree a -> FingerTree a
(<||) = reducer (<|)

(||>) :: (Reduce f) => FingerTree a -> f a -> FingerTree a
(||>) = reducel (|>)

toTree :: (Reduce f) => f a -> FingerTree a
toTree s = s <|| Empty

a <| Deep [b,c,d,e] m sf = Deep [a,b] (Node3 c d e <| m) sf

这一行比较关键,意思是说,这一层的Digit装不下了,就把这个Digit里拿出3个元素,
做个大Node,作为一个元素,插入到下一层去。这保证了FingerTree越往下,节点越大的性质。也就保证了O(logN)复杂度

这个toTree的实现也很有意思,

(<|) :: a -> FingerTree a -> FingerTree a
reducer (<|) 就变成了 f a -> FingerTree a -> FingerTree a

出队

To deconstruct a sequence, we define a type that expresses a view of the left end
of a sequence as either empty or an element together with the rest of the sequence:

Then we can define separate functions isEmpty, head L , and tail L using the view:

In a lazy language like Haskell, the tail part of the view is not computed unless it
is used. In a strict language, it might be more useful to provide the three separate
functions as primitives.

data ViewL s a = NilL | ConsL a (s a)
data ViewR s a = NilR | ConsR (s a) a

viewL :: FingerTree a -> ViewL FingerTree a
viewL Empty = NilL
viewL (Single x) = ConsL x Empty
viewL (Deep pr m sf) = ConsL (head pr) (deepL (tail pr) m sf)

viewR :: FingerTree a -> ViewR FingerTree a
viewR Empty = NilR
viewR (Single x) = ConsR Empty x
viewR (Deep pr m sf) = ConsR (deepR pr m (init sf)) (last sf)

deepL :: [a] -> FingerTree (Node a) -> Digit a -> FingerTree a
deepL [] m sf  =
  case viewL m of
    NilL -> toTree sf
    ConsL a mbar -> Deep (toList a) mbar sf
deepL pr m sf = Deep pr m sf

deepR :: [a] -> FingerTree (Node a) -> Digit a -> FingerTree a
deepR pr m [] =
  case viewR m of
    NilR -> toTree pr
    ConsR mbar a -> Deep pr mbar (toList a)
deepR pr m sf = Deep pr m sf

isEmpty :: FingerTree a -> Bool
isEmpty x = case viewL x of
  NilL -> True
  ConsL _ _ -> False

headL :: FingerTree a -> a
headL x = case viewL x of ConsL a _ -> a

tailL :: FingerTree a -> FingerTree a
tailL x = case viewL x of ConsL _ x' -> x'

lastR :: FingerTree a -> a
lastR x = case viewR x of ConsR _ a -> a

initR :: FingerTree a -> FingerTree a
initR x = case viewR x of ConsR x' _ -> x'

3.3 Concatenation

The only difficult case is concatenation of two Deep trees.

We can
use the prefix of the first tree as the prefix of the result, and the suffix of the second
tree as the suffix of the result. To combine the rest to make the new middle subtree,
we require a function of type

FingerTree (Node a) → Digit a → Digit a → FingerTree (Node a) →
FingerTree (Node a)

中间的Digit a → Digit a可以简化成一个 [a]

app3 :: FingerTree a -> [a] -> FingerTree a -> FingerTree a
app3 Empty ts xs = ts <|| xs
app3 xs ts Empty = xs ||> ts
app3 (Single x) ts xs = x <| (ts <|| xs)
app3 xs ts (Single x) = (xs ||> ts) |> x
app3 (Deep pr1 m1 sf1) ts (Deep pr2 m2 sf2) =
  Deep pr1 (app3 m1 (nodes (sf1 ++ ts ++ pr2)) m2) sf2

nodes :: [a] -> [Node a]
nodes [a,b] = [Node2 a b]
nodes [a,b,c] = [Node3 a b c]
nodes [a,b,c,d] = [Node2 a b,Node2 c d]
nodes (a:b:c:xs) = Node3 a b c : nodes xs

(><) :: FingerTree a -> FingerTree a -> FingerTree a
xs >< ys = app3 xs [] ys

Deep pr1 (app3 m1 (nodes (sf1 ++ ts ++ pr2)) m2) sf2
这一句话里,使用nodes把这一层的几个元素,"包装"成Node作为下一层的元素使用

顺便实现让FingerTree作为Monoid使用

instance Monoid (FingerTree a) where
  mempty = Empty
  mappend = (><)

参考链接

[1] https://www.zhihu.com/question/32163076

[2] http://www.staff.city.ac.uk/~ross/papers/FingerTree.pdf

[3] https://en.wikipedia.org/wiki/Monoid

[4] http://www.staff.city.ac.uk/~ross/papers/FingerTree/more-trees.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,440评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,814评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,427评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,710评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,625评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,511评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,162评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,311评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,262评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,278评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,989评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,583评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,664评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,904评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,274评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,856评论 2 339

推荐阅读更多精彩内容