Tree#

class discopy.grammar.cfg.Tree(root, *branches)[source]#

Bases: object

A tree is a rule for the root and a list of trees called branches.

Example

We build a syntax tree from a context-free grammar.

>>> n, d, v = Ty('N'), Ty('D'), Ty('V')
>>> vp, np, s = Ty('VP'), Ty('NP'), Ty('S')
>>> Caesar, crossed = Word('Caesar', n), Word('crossed', v)
>>> the, Rubicon = Word('the', d), Word('Rubicon', n)
>>> VP, NP = Rule(n @ v, vp), Rule(d @ n, np)
>>> S = Rule(vp @ np, s)
>>> sentence = S(VP(Caesar, crossed), NP(the, Rubicon))
Parameters:
ty_factory#

alias of Ty

to_diagram(contravariant=False)[source]#

Interface between Tree and monoidal.Diagram.

>>> x = Ty('x')
>>> f = Rule(x @ x, x, name='f')
>>> tree = f(f(f, f), f)
>>> tree.to_diagram().foliation().draw(
...     path='docs/_static/grammar/tree-to-diagram.png')
../_images/tree-to-diagram.png
Return type:

Diagram

static from_nltk(tree, lexicalised=True, word_types=False)[source]#

Interface with NLTK

>>> import nltk
>>> t = nltk.Tree.fromstring("(S (NP I) (VP (V saw) (NP him)))")
>>> print(Tree.from_nltk(t))
S(I, VP(saw, him))
>>> Tree.from_nltk(t).branches[0]
grammar.cfg.Word('I', monoidal.Ty(cat.Ob('NP')))
Parameters:

tree (nltk.Tree) –

Return type:

Tree

factory#

alias of Tree