Scalaz(24)- 泛函数据结构: Tree-数据游览及敬服

何为Miller Rabin算法

先是看一下度娘的表明(假使你懒得读直接跳过就足以反正也没啥乱用:joy:)

米尔er-Rabin算法是眼下主流的基于概率的素数测试算法,在构建密码安全系统中占据首要的地位。通过相比各样素数测试算法和对Miller-Rabin算法举办的精雕细刻探究,表明在微机中构建密码安全部系时,
Miller-Rabin算法是完结素数测试的特级接纳。通过对Miller-Rabin 算
法底层运算的优化,可以得到较过去贯彻更好的特性。[1]  随着音信技术的升华、网络的推广和电子商务的举办,
消息安全逐渐显示出了其首要。音信的泄密、伪造、篡改
等问题会给消息的官方拥有者带来紧要的损失。在处理器中构建密码安全序列可以提供4种最主题的保障信息安全的服
务:保密性、数据完整性、鉴别、抗抵赖性,从而可以很大
程度上爱护用户的数额安全。在密码安全体系中,公开密钥
算法在密钥交流、密钥管理、身份评释等问题的处理上最为有效,因而在方方面面系统中占据紧要的身份。如今的当众密钥
算法大部分按照大整数分解、有限域上的离散对数问题和椭
圆曲线上的离散对数问题,那么些数学难题的构建大部分都需
要生成一种超大的素数,尤其在经典的RSA算法中,生成的素数的质地对系统的安全性有很大的震慑。近来大素数的生
成,尤其是任意大素数的变动重倘诺应用素数测试算法,本
文首要针对当前主流的Miller-Rabin 算法进行周全系统的辨析
和切磋,并对其实现举办了优化

简短米尔(Mill)er
Rabin算法在音信学奥赛中的应用就一句话:

看清一个数是否是素数

object Tree extends TreeInstances with TreeFunctions {
  /** Construct a tree node with no children. */
  def apply[A](root: => A): Tree[A] = leaf(root)

  object Node {
    def unapply[A](t: Tree[A]): Option[(A, Stream[Tree[A]])] = Some((t.rootLabel, t.subForest))
  }
}

正确性

创办者告诉大家:joy::若$p$通过两次测试,则$p$不是素数的几率为$25$%

这就是说通过$t$轮测试,$p$不是素数的几率为$\dfrac
{1}{4^{t}}$

本人习惯用$2,3,5,7,11,13,17,19$这一个数举办判断

在讯息学范围内出错率为$0$%(不带高精:joy:)

 

code

小心在拓展素数判断的时候需要采取连忙幂。。

其一理应比较简单,就不细讲了

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#define LL long long 
using namespace std;
const LL MAXN=2*1e7+10;
const LL INF=1e7+10;
inline char nc()
{
    static char buf[MAXN],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,MAXN,stdin),p1==p2)?EOF:*p1++;
}
inline LL read()
{
    char c=nc();LL x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=nc();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=nc();}
    return x*f;
}
LL fastpow(LL a,LL p,LL mod)
{
    LL base=1;
    while(p)
    {
        if(p&1) base=(base*a)%mod;
        a=(a*a)%mod;
        p>>=1;
    }
    return base;
}
LL num[]= {2,3,5,7,11,13,17,19};
bool Miller_Rabin(LL n)
{
    if (n==2) return 1;
    if((n&1)==0||n==1) return false;
    for (LL i=0; i<8; i++) if (n==num[i]) return 1;

    LL temp=n-1,t=0,nxt;
    while((temp&1)==0) temp>>=1,t++;

    for(LL i=0;i<8;i++)
    {
        LL a=num[i];
        LL now=fastpow(a,temp,n);
        nxt=now;
        for(LL j=1;j<=t;j++)
        {
            nxt=(now*now)%n;
            if(nxt==1&&now!=n-1&&now!=1) return false;
            now=nxt;
        }
        if(now!=1) return false;
    }
    return true;
}
int main()
{
    #ifdef WIN32
    freopen("a.in","r",stdin);
    #else
    #endif 
    LL N=read(),M=read();
    while(M--)
    {
        LL opt=read();
        if(Miller_Rabin(opt))    printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}

据称那一个pathTree函数能把List里的目录结构转化成Tree。先看看究竟是不是具有这样效率:

定理

Miller
Rabin算法的依照是费马小定理:

$$a^{p-1}\equiv 1\left(
modP\right)$$

证明:

特性1:$p-1$个整数$a,2a,3a,…(p-1)a$中尚无一个是$p$的倍数 

属性2:$a,2a,3a,…(p-1)a$中没有其余六个同余与模$p$的

所以$a,2a,3a,…(p-1)a$对模$p$的同余既不为零,也一向不六个同余一模一样

从而,这$p-1$个数模$p$的同余一定是$a,2a,3a,…(p-1)a$的某一种排列

即$a,2a,3a,…(p-1)a \equiv
{1,2,3,…,p-1}! (mod p)$

化简为

$a^{p-1}*(p-1)! \equiv {p-1}! (mod
p)$

基于威尔逊(威尔逊)定理可知$(p-1)!$与$p$互质,所以还要约去$(p-1)!$

即得到$a^{p-1}\equiv 1\left(
modP\right)$

 

那就是说是不是当一个数$p$满意任意$a$使得$a^{p-1}\equiv
1\left( modP\right)$创设的时候它就是素数呢?

在费马小定理被声明后的很长一段时间里,人们都以为那是很彰着的,

然则毕竟有一天,人们给出了反例 ,推翻了这些结论

 

这是否代表利用费马小定理的合计去判断素数的研究就是荒谬的呢?

答案是自然的。

唯独一旦我们得以人工的把出错率降到非凡小吗?

例如,对于一个数,我们有$99.99999$%的几率做出科学判断,这这种算法不也很优越么?

 

于是乎Miller Rabin算法诞生了!

 

率先介绍一下二次探测定理

若$p$为素数,$a^{2}\equiv 1\left(
modP\right)$,那么$a\equiv \pm 1\left( modP\right)$

证明

$a^{2}\equiv 1\left(
modP\right)$

$a^{2}-1\equiv 0\left(
modP\right)$

$(a+1)*(a-1)\equiv 0\left(
modP\right)$

那么

$(a+1)\equiv 0\left(
modP\right)$

或者

$(a-1)\equiv 0\left(
modP\right)$

(此处可依照唯一分解定理申明)

$a\equiv \pm 1\left(
modP\right)$

 

其一定律和素数判定有什么用吧?

先是,遵照Miller Rabin算法的长河

尽管需要看清的数是$p$

(博主乱入:以下内容较肤浅,请仔细领悟:joy:)

我们把$p-1$分解为$2^k*t$的形式

然后轻易挑选一个数$a$,总结出$a^t mod
p$

让其相连的$*2$,同时组成二次探测定理进行判断

假使我们$*2$后的数$mod p ==
1$,然而往日的数$mod p != \pm 1$

那么这几个数就是合数(违背了二次探测定理)

这样乘$k$次,最终收获的数就是$a^{p-1}$

这就是说只要最后总结出的数不为$1$,这个数也是合数(费马小定理)

* A multi-way tree, also known as a rose tree. Also known as Cofree[Stream, A].
 */
sealed abstract class Tree[A] {

  import Tree._

  /** The label at the root of this tree. */
  def rootLabel: A

  /** The child nodes of this tree. */
  def subForest: Stream[Tree[A]]
...

 

1  "root".node(
2      "A".node(List().toSeq: _*),
3      "B".node(List().toSeq: _*)
4      ) drawTree                                   //> res4: String = ""root"
5                                                   //| |
6                                                   //| +- "A"
7                                                   //| |
8                                                   //| `- "B"
9                                                   //| "

 

TreeLoc的游动函数:

树形集合游标TreeLoc由最近节点tree、左子树lefts、右子树rights及父树parents组成。lefts,rights,parents都是在流中的树形Stream[Tree[A]]。
用Tree.loc可以直接对目标树生成TreeLoc:

 1   val paths = List(List("A","a1","a2"),List("B","b1"))
 2                                                   //> paths  : List[List[String]] = List(List(A, a1, a2), List(B, b1))
 3   pathTree("root",paths) drawTree                 //> res0: String = ""root"
 4                                                   //| |
 5                                                   //| +- "A"
 6                                                   //| |  |
 7                                                   //| |  `- "a1"
 8                                                   //| |     |
 9                                                   //| |     `- "a2"
10                                                   //| |
11                                                   //| `- "B"
12                                                   //|    |
13                                                   //|    `- "b1"
14                                                   //| "
15  val paths = List(List("A","a1","a2"),List("B","b1"),List("B","b2","b3"))
16              //> paths  : List[List[String]] = List(List(A, a1, a2), List(B, b1), List(B, b2,
17                                                   //|  b3))
18   pathTree("root",paths) drawTree                 //> res0: String = ""root"
19                                                   //| |
20                                                   //| +- "A"
21                                                   //| |  |
22                                                   //| |  `- "a1"
23                                                   //| |     |
24                                                   //| |     `- "a2"
25                                                   //| |
26                                                   //| `- "B"
27                                                   //|    |
28                                                   //|    +- "b2"
29                                                   //|    |  |
30                                                   //|    |  `- "b3"
31                                                   //|    |
32                                                   //|    `- "b1"
33                                                   //| "

说到构建Tree,偶然在网上发现了这么一个Tree构建函数:

用法示范:

 

 

 1  val tree: Tree[Int] =
 2     1.node(
 3       11.leaf,
 4       12.node(
 5         121.leaf),
 6      2.node(
 7       21.leaf,
 8       22.leaf)
 9      )                                            //> tree  : scalaz.Tree[Int] = <tree>
10   tree.loc                                        //> res7: scalaz.TreeLoc[Int] = TreeLoc(<tree>,Stream(),Stream(),Stream())
11   val l = for {
12    l1 <- tree.loc.some
13    l2 <- l1.firstChild
14    l3 <- l1.lastChild
15    l4 <- l3.firstChild
16    } yield (l1,l2,l3,l4)                          //> l  : Option[(scalaz.TreeLoc[Int], scalaz.TreeLoc[Int], scalaz.TreeLoc[Int],
17                                                   //|  scalaz.TreeLoc[Int])] = Some((TreeLoc(<tree>,Stream(),Stream(),Stream()),T
18                                                   //| reeLoc(<tree>,Stream(),Stream(<tree>, <tree>),Stream((Stream(),1,Stream()),
19                                                   //|  ?)),TreeLoc(<tree>,Stream(<tree>, <tree>),Stream(),Stream((Stream(),1,Stre
20                                                   //| am()), ?)),TreeLoc(<tree>,Stream(),Stream(<tree>, ?),Stream((Stream(<tree>,
21                                                   //|  <tree>),2,Stream()), ?))))
22   
23   l.get._1.getLabel                               //> res8: Int = 1
24   l.get._2.getLabel                               //> res9: Int = 11
25   l.get._3.getLabel                               //> res10: Int = 2
26   l.get._4.getLabel                               //> res11: Int = 21

 合并目录:

 

final case class TreeLoc[A](tree: Tree[A], lefts: TreeForest[A],
                            rights: TreeForest[A], parents: Parents[A]) {
...
trait TreeLocFunctions {
  type TreeForest[A] =
  Stream[Tree[A]]

  type Parent[A] =
  (TreeForest[A], A, TreeForest[A])

  type Parents[A] =
  Stream[Parent[A]]

 

 1   val tree: Tree[Int] =
 2     1.node(
 3       11.leaf,
 4       12.node(
 5         121.leaf),
 6      2.node(
 7       21.leaf,
 8       22.leaf)
 9      )                                            //> tree  : scalaz.Tree[Int] = <tree>
10   tree.loc                                        //> res7: scalaz.TreeLoc[Int] = TreeLoc(<tree>,Stream(),Stream(),Stream())
11   val l = for {
12    l1 <- tree.loc.some
13    l2 <- l1.find{_.getLabel == 2}
14    l3 <- l1.find{_.getLabel == 121}
15    l4 <- l2.find{_.getLabel == 22}
16    l5 <- l1.findChild{_.rootLabel == 12}
17    l6 <- l1.findChild{_.rootLabel == 2}
18   } yield l6                                      //> l  : Option[scalaz.TreeLoc[Int]] = Some(TreeLoc(<tree>,Stream(<tree>, ?),St
19                                                   //| ream(),Stream((Stream(),1,Stream()), ?)))

 

 

  def root: TreeLoc[A] =
    parent match {
      case Some(z) => z.root
      case None    => this
    }

  /** Select the left sibling of the current node. */
  def left: Option[TreeLoc[A]] = lefts match {
    case t #:: ts     => Some(loc(t, ts, tree #:: rights, parents))
    case Stream.Empty => None
  }

  /** Select the right sibling of the current node. */
  def right: Option[TreeLoc[A]] = rights match {
    case t #:: ts     => Some(loc(t, tree #:: lefts, ts, parents))
    case Stream.Empty => None
  }

  /** Select the leftmost child of the current node. */
  def firstChild: Option[TreeLoc[A]] = tree.subForest match {
    case t #:: ts     => Some(loc(t, Stream.Empty, ts, downParents))
    case Stream.Empty => None
  }

  /** Select the rightmost child of the current node. */
  def lastChild: Option[TreeLoc[A]] = tree.subForest.reverse match {
    case t #:: ts     => Some(loc(t, ts, Stream.Empty, downParents))
    case Stream.Empty => None
  }

  /** Select the nth child of the current node. */
  def getChild(n: Int): Option[TreeLoc[A]] =
    for {lr <- splitChildren(Stream.Empty, tree.subForest, n)
         ls = lr._1
    } yield loc(ls.head, ls.tail, lr._2, downParents)

这就是说Tree就是个Monad,也是Functor,Applicative,如故traversable,foldable。Tree也实现了Order,Equal实例,能够开展值的一一相比。咱们就用些例子来验证呢: 

 1   val paths = List(List("A","a1"),List("A","a2")) //> paths  : List[List[String]] = List(List(A, a1), List(A, a2))
 2   val gpPaths =paths.groupBy(_.head)              //> gpPaths  : scala.collection.immutable.Map[String,List[List[String]]] = Map(A
 3                                                   //|  -> List(List(A, a1), List(A, a2)))
 4   List(List("A","a1"),List("A","a2")) collect { case pp +: rest if rest.nonEmpty => rest }
 5                                                   //> res0: List[List[String]] = List(List(a1), List(a2))
 6 
 7 //相当产生结果
 8 "root".node(
 9        "A".node(
10           "a1".node(
11            List().toSeq: _*)
12            ,
13           "a2".node(
14            List().toSeq: _*)
15            )
16        ) drawTree                                 //> res3: String = ""root"
17                                                   //| |
18                                                   //| `- "A"
19                                                   //|    |
20                                                   //|    +- "a1"
21                                                   //|    |
22                                                   //|    `- "a2"
23                                                   //| "

大家试着用这多少个函数游动:

 

 

 

 

实在注入方法调用了Tree里的构建函数:

 

我们可以直接构建Tree:

 1   val tree: Tree[Int] =
 2     1.node(
 3       11.leaf,
 4       12.node(
 5         121.leaf),
 6      2.node(
 7       21.leaf,
 8       22.leaf)
 9      )                                            //> tree  : scalaz.Tree[Int] = <tree>
10    def modTree(t: Tree[Int]): Tree[Int] = {
11       val l = for {
12         l1 <- t.loc.some
13         l2 <- l1.find{_.getLabel == 22}
14         l3 <- l2.setTree { 3.node (31.leaf) }.some
15       } yield l3
16       l.get.toTree
17    }                                              //> modTree: (t: scalaz.Tree[Int])scalaz.Tree[Int]
18    val l = for {
19    l1 <- tree.loc.some
20    l2 <- l1.find{_.getLabel == 2}
21    l3 <- l2.modifyTree{modTree(_)}.some
22    l4 <- l3.root.some
23    l5 <- l4.find{_.getLabel == 12}
24    l6 <- l5.delete
25   } yield l6                                      //> l  : Option[scalaz.TreeLoc[Int]] = Some(TreeLoc(<tree>,Stream(<tree>, ?),St
26                                                   //| ream(),Stream((Stream(),1,Stream()), ?)))
27   l.get.toTree.drawTree                           //> res7: String = "1
28                                                   //| |
29                                                   //| +- 11
30                                                   //| |
31                                                   //| `- 2
32                                                   //|    |
33                                                   //|    +- 21
34                                                   //|    |
35                                                   //|    `- 3
36                                                   //|       |
37                                                   //|       `- 31
38                                                   //| "

 

 1  Tree("ALeaf") === "ALeaf".leaf                  //> res5: Boolean = true
 2   val tree: Tree[Int] =
 3     1.node(
 4       11.leaf,
 5       12.node(
 6         121.leaf),
 7      2.node(
 8       21.leaf,
 9       22.leaf)
10      )                                            //> tree  : scalaz.Tree[Int] = <tree>
11   tree.drawTree                                   //> res6: String = "1
12                                                   //| |
13                                                   //| +- 11
14                                                   //| |
15                                                   //| +- 12
16                                                   //| |  |
17                                                   //| |  `- 121
18                                                   //| |
19                                                   //| `- 2
20                                                   //|    |
21                                                   //|    +- 21
22                                                   //|    |
23                                                   //|    `- 22
24                                                   //| "

find用法示范:

 

 

Tree是由一个A值rootLabel及一个流中子树Stream[Tree[A]]整合。Tree可以只由一个A类型值rootLabel组成,这时流中子树subForest就是空的Stream.empty。只有rootLabel的Tree俗称叶(leaf),有subForest的称为节(node)。scalaz为其余项目提供了leaf和node的构建注入方法:syntax/TreeOps.scala

Tree提供了构建和情势拆分函数:

 

跳动函数:

 

 

 

  /** Replace the current node with the given one. */
  def setTree(t: Tree[A]): TreeLoc[A] = loc(t, lefts, rights, parents)

  /** Modify the current node with the given function. */
  def modifyTree(f: Tree[A] => Tree[A]): TreeLoc[A] = setTree(f(tree))

  /** Modify the label at the current node with the given function. */
  def modifyLabel(f: A => A): TreeLoc[A] = setLabel(f(getLabel))

  /** Get the label of the current node. */
  def getLabel: A = tree.rootLabel

  /** Set the label of the current node. */
  def setLabel(a: A): TreeLoc[A] = modifyTree((t: Tree[A]) => node(a, t.subForest))

  /** Insert the given node to the left of the current node and give it focus. */
  def insertLeft(t: Tree[A]): TreeLoc[A] = loc(t, lefts, Stream.cons(tree, rights), parents)

  /** Insert the given node to the right of the current node and give it focus. */
  def insertRight(t: Tree[A]): TreeLoc[A] = loc(t, Stream.cons(tree, lefts), rights, parents)

  /** Insert the given node as the first child of the current node and give it focus. */
  def insertDownFirst(t: Tree[A]): TreeLoc[A] = loc(t, Stream.Empty, tree.subForest, downParents)

  /** Insert the given node as the last child of the current node and give it focus. */
  def insertDownLast(t: Tree[A]): TreeLoc[A] = loc(t, tree.subForest.reverse, Stream.Empty, downParents)

  /** Insert the given node as the nth child of the current node and give it focus. */
  def insertDownAt(n: Int, t: Tree[A]): Option[TreeLoc[A]] =
    for (lr <- splitChildren(Stream.Empty, tree.subForest, n)) yield loc(t, lr._1, lr._2, downParents)

  /** Delete the current node and all its children. */
  def delete: Option[TreeLoc[A]] = rights match {
    case Stream.cons(t, ts) => Some(loc(t, lefts, ts, parents))
    case _                  => lefts match {
      case Stream.cons(t, ts) => Some(loc(t, ts, rights, parents))
      case _                  => for (loc1 <- parent) yield loc1.modifyTree((t: Tree[A]) => node(t.rootLabel, Stream.Empty))
    }
  }
  /** Select the nth child of the current node. */
  def getChild(n: Int): Option[TreeLoc[A]] =
    for {lr <- splitChildren(Stream.Empty, tree.subForest, n)
         ls = lr._1
    } yield loc(ls.head, ls.tail, lr._2, downParents)

  /** Select the first immediate child of the current node that satisfies the given predicate. */
  def findChild(p: Tree[A] => Boolean): Option[TreeLoc[A]] = {
    @tailrec
    def split(acc: TreeForest[A], xs: TreeForest[A]): Option[(TreeForest[A], Tree[A], TreeForest[A])] =
      (acc, xs) match {
        case (acc, Stream.cons(x, xs)) => if (p(x)) Some((acc, x, xs)) else split(Stream.cons(x, acc), xs)
        case _                         => None
      }
    for (ltr <- split(Stream.Empty, tree.subForest)) yield loc(ltr._2, ltr._1, ltr._3, downParents)
  }

  /**Select the first descendant node of the current node that satisfies the given predicate. */
  def find(p: TreeLoc[A] => Boolean): Option[TreeLoc[A]] =
    Cobind[TreeLoc].cojoin(this).tree.flatten.find(p)

果不其然能行,而且仍可以把”B”节点合并会聚。这个函数的撰稿人简直就是个神人,起码是个算法和FP语法运用大师。我尽管还不可能达成大师的档次能写出如此的泛函程序,但好奇心是挡不住的,总想理解这么些函数是怎么运作的。可以用部分测试数据来渐渐跟踪一下: 

 

 1   val tr = 1.leaf                                 //> tr  : scalaz.Tree[Int] = <tree>
 2   val tl = for {
 3     l1 <- tr.loc.some
 4     l3 <- l1.insertDownLast(12.leaf).some
 5     l4 <- l3.insertDownLast(121.leaf).some
 6     l5 <- l4.root.some
 7     l2 <- l5.insertDownFirst(11.leaf).some
 8     l6 <- l2.root.some
 9     l7 <- l6.find{_.getLabel == 12}
10     l8 <- l7.setLabel(102).some
11   } yield l8                                      //> tl  : Option[scalaz.TreeLoc[Int]] = Some(TreeLoc(<tree>,Stream(<tree>, ?),S
12                                                   //| tream(),Stream((Stream(),1,Stream()), ?)))
13   
14   tl.get.toTree.drawTree                          //> res8: String = "1
15                                                   //| |
16                                                   //| +- 11
17                                                   //| |
18                                                   //| `- 102
19                                                   //|    |
20                                                   //|    `- 121
21                                                   //| "
22   

 

trait TreeFunctions {
  /** Construct a new Tree node. */
  def node[A](root: => A, forest: => Stream[Tree[A]]): Tree[A] = new Tree[A] {
    lazy val rootLabel = root
    lazy val subForest = forest

    override def toString = "<tree>"
  }

  /** Construct a tree node with no children. */
  def leaf[A](root: => A): Tree[A] = node(root, Stream.empty)

 

 

 1 // 是 Functor...
 2     (tree map { v: Int => v + 1 }) ===
 3     2.node(
 4       12.leaf,
 5       13.node(
 6         122.leaf),
 7      3.node(
 8       22.leaf,
 9       23.leaf)
10      )                                            //> res7: Boolean = true
11 
12  // ...是 Monad
13     1.point[Tree] === 1.leaf                      //> res8: Boolean = true
14     val t2 = tree >>= (x => (x == 2) ? x.leaf | x.node((-x).leaf))
15                                                   //> t2  : scalaz.Tree[Int] = <tree>
16     t2 === 1.node((-1).leaf, 2.leaf, 3.node((-3).leaf, 4.node((-4).leaf)))
17                                                   //> res9: Boolean = false
18     t2.drawTree                                   //> res10: String = "1
19                                                   //| |
20                                                   //| +- -1
21                                                   //| |
22                                                   //| +- 11
23                                                   //| |  |
24                                                   //| |  `- -11
25                                                   //| |
26                                                   //| +- 12
27                                                   //| |  |
28                                                   //| |  +- -12
29                                                   //| |  |
30                                                   //| |  `- 121
31                                                   //| |     |
32                                                   //| |     `- -121
33                                                   //| |
34                                                   //| `- 2
35                                                   //|    |
36                                                   //|    +- 21
37                                                   //|    |  |
38                                                   //|    |  `- -21
39                                                   //|    |
40                                                   //|    `- 22
41                                                   //|       |
42                                                   //|       `- -22
43                                                   //| "
44  // ...是 Foldable
45     tree.foldMap(_.toString) === "1111212122122"  //> res11: Boolean = true
  def pathTree[E](root: E, paths: Seq[Seq[E]]): Tree[E] = {
    root.node(paths groupBy (_.head) map {
      case (parent, subpaths) =>
        pathTree(parent, subpaths collect {
          case pp +: rest if rest.nonEmpty => rest
        })
    } toSeq: _*)
  }

 

Tree实现了下边众多的接口函数:

加多一层: 

 1 /** A TreeLoc zipper of this tree, focused on the root node. */
 2   def loc: TreeLoc[A] = TreeLoc.loc(this, Stream.Empty, Stream.Empty, Stream.Empty)
 3  
 4  val tree: Tree[Int] =
 5     1.node(
 6       11.leaf,
 7       12.node(
 8         121.leaf),
 9      2.node(
10       21.leaf,
11       22.leaf)
12      )                           //> tree  : scalaz.Tree[Int] = <tree>
13 
14   tree.loc                      //> res7: scalaz.TreeLoc[Int] = TreeLoc(<tree>,Stream(),Stream(),Stream())

 

因而地点的跟踪约化我们看出List(List(A))在pathTree里的施行进程。这里把纷繁的groupBy和collect函数的用法和结果领会了。实际上任何经过相当于:

留意:上边6个跳动都成功了。假诺不可以跳转结果会是None
insert,modify,delete这么些操作函数:

1   val paths = List(List("A"))           //> paths  : List[List[String]] = List(List(A))
2   val gpPaths =paths.groupBy(_.head)    //> gpPaths  : scala.collection.immutable.Map[String,List[List[String]]] = Map(A-> List(List(A)))
3   List(List("A")) collect { case pp +: rest if rest.nonEmpty => rest }
4                                                   //> res0: List[List[String]] = List()
sealed abstract class TreeInstances {
  implicit val treeInstance: Traverse1[Tree] with Monad[Tree] with Comonad[Tree] with Align[Tree] with Zip[Tree] = new Traverse1[Tree] with Monad[Tree] with Comonad[Tree] with Align[Tree] with Zip[Tree] {
    def point[A](a: => A): Tree[A] = Tree.leaf(a)
    def cobind[A, B](fa: Tree[A])(f: Tree[A] => B): Tree[B] = fa cobind f
    def copoint[A](p: Tree[A]): A = p.rootLabel
    override def map[A, B](fa: Tree[A])(f: A => B) = fa map f
    def bind[A, B](fa: Tree[A])(f: A => Tree[B]): Tree[B] = fa flatMap f
    def traverse1Impl[G[_]: Apply, A, B](fa: Tree[A])(f: A => G[B]): G[Tree[B]] = fa traverse1 f
    override def foldRight[A, B](fa: Tree[A], z: => B)(f: (A, => B) => B): B = fa.foldRight(z)(f)
    override def foldMapRight1[A, B](fa: Tree[A])(z: A => B)(f: (A, => B) => B) = (fa.flatten.reverse: @unchecked) match {
      case h #:: t => t.foldLeft(z(h))((b, a) => f(a, b))
    }
    override def foldLeft[A, B](fa: Tree[A], z: B)(f: (B, A) => B): B =
      fa.flatten.foldLeft(z)(f)
    override def foldMapLeft1[A, B](fa: Tree[A])(z: A => B)(f: (B, A) => B): B = fa.flatten match {
      case h #:: t => t.foldLeft(z(h))(f)
    }
    override def foldMap[A, B](fa: Tree[A])(f: A => B)(implicit F: Monoid[B]): B = fa foldMap f
    def alignWith[A, B, C](f: (\&/[A, B]) ⇒ C) = { 
      def align(ta: Tree[A], tb: Tree[B]): Tree[C] =
        Tree.node(f(\&/(ta.rootLabel, tb.rootLabel)), Align[Stream].alignWith[Tree[A], Tree[B], Tree[C]]({
          case \&/.This(sta) ⇒ sta map {a ⇒ f(\&/.This(a))}
          case \&/.That(stb) ⇒ stb map {b ⇒ f(\&/.That(b))}
          case \&/.Both(sta, stb) ⇒ align(sta, stb)
        })(ta.subForest, tb.subForest))
      align _
    }
    def zip[A, B](aa: => Tree[A], bb: => Tree[B]) = {
      val a = aa
      val b = bb
      Tree.node(
        (a.rootLabel, b.rootLabel),
        Zip[Stream].zipWith(a.subForest, b.subForest)(zip(_, _))
      )
    }
  }

  implicit def treeEqual[A](implicit A0: Equal[A]): Equal[Tree[A]] =
    new TreeEqual[A] { def A = A0 }

  implicit def treeOrder[A](implicit A0: Order[A]): Order[Tree[A]] =
    new Order[Tree[A]] with TreeEqual[A] {
      def A = A0
      import std.stream._
      override def order(x: Tree[A], y: Tree[A]) =
        A.order(x.rootLabel, y.rootLabel) match {
          case Ordering.EQ =>
            Order[Stream[Tree[A]]].order(x.subForest, y.subForest)
          case x => x
        }
    }

 

setTree和delete会替换当前节点下的持有子树:

final class TreeOps[A](self: A) {
  def node(subForest: Tree[A]*): Tree[A] = Tree.node(self, subForest.toStream)

  def leaf: Tree[A] = Tree.leaf(self)
}

trait ToTreeOps {
  implicit def ToTreeOps[A](a: A) = new TreeOps(a)
}

相信那么些跟踪过程丰硕精晓整个函数的劳作规律了。
有了Tree构建模式后就需要Tree的游动和操作函数了。与串形集合的直线游动不同的是,树形集合游动模式是分岔的。所以Zipper不太适用于树形结构。scalaz特别提供了树形集合的定点游标TreeLoc,咱们看看它的概念:scalaz/TreeLoc.scala

1  "root".node(
2        "A".node(List().toSeq: _*)
3        ) drawTree                                 //> res3: String = ""root"
4                                                   //| |
5                                                   //| `- "A"
6                                                   //| "

 

 
上节我们谈论了Zipper-串形不可变集合(immutable sequential
collection)游标,在串形集合中左右游走及要素维护操作。这篇我们研讨Tree。在电子商务应用中对于xml,json等格式文件的处理要求特别之广泛,scalaz提供了Tree数据类型及相关的观光及操作函数能更有益于急迅的拍卖xml,json文件及系统目录这多少个树形结构数据的相干编程。scalaz
Tree的概念极度简单:scalaz/Tree.scala

经过scalaz的Tree和TreeLoc数据结构,以及一整套树形结构游览、操作函数,我们可以一本万利有效地促成FP风格的不足变树形集合编程。

一旦再增添一个点就相当于:

 

 1   val paths = List(List("A","a1"))                //> paths  : List[List[String]] = List(List(A, a1))
 2   val gpPaths =paths.groupBy(_.head)              //> gpPaths  : scala.collection.immutable.Map[String,List[List[String]]] = Map(A
 3                                                   //|  -> List(List(A, a1)))
 4   List(List("A","a1")) collect { case pp +: rest if rest.nonEmpty => rest }
 5                                                   //> res0: List[List[String]] = List(List(a1))
 6 
 7 //化解成
 8  "root".node(
 9        "A".node(
10           "a1".node(
11            List().toSeq: _*)
12            )
13        ) drawTree                                 //> res3: String = ""root"
14                                                   //| |
15                                                   //| `- "A"
16                                                   //|    |
17                                                   //|    `- "a1"
18                                                   //| "

 

 

Leave a Comment.