Function Repository Resource:

FoldGraph

Source Notebook

Construct a graph by folding a list of arguments

Contributed by: Nikolay Murzin

ResourceFunction["FoldGraph"][f,{x1,x2,},{y1,y2,}]

constructs a graph with edges for each output of a multioutput function f applied to inputs xi and iteratively to each yi.

ResourceFunction["FoldGraph"][f,x,{y1,y2,}]

is equivalent to ResourceFunction["FoldGraph"][f,{x},{y1,y2,}].

ResourceFunction["FoldGraph"][f,{x,y1,y2,}]

is equivalent to ResourceFunction["FoldGraph"][f,{x},{y1,y2,}].

ResourceFunction["FoldGraph"][f]

represents an operator form of ResourceFunction["FoldGraph"] that can be applied to expressions.

Details and Options

Given that for each ith input at jth iteration the kth output of a function is denoted as ok, j=fk[oi, j-1,yj] where fkis the kth part of f. Initial outputs are the inputs oi, 0=xi, the resulting graph contains all edges connecting subsequent iterations oi,j-1 ok, j.
ResourceFunction["FoldGraph"][f,{}] produces an empty graph.
For every output of a function that has a Labeled head, take its first argument as a vertex and tag a corresponding edge with its second argument. The default head can be changed with the "TagHead" option of ResourceFunction["FoldGraph"].
ResourceFunction["FoldGraph"] supports all options of Graph.

Examples

Basic Examples (6) 

Fold a single output function to make a graph:

In[1]:=
ResourceFunction["FoldGraph"][f, x, {a, b, c}, VertexLabels -> Automatic]
Out[1]=

Use the first element of the list as an initial vertex:

In[2]:=
ResourceFunction["FoldGraph"][f, {a, b, c}, VertexLabels -> Automatic]
Out[2]=

Fold with multiple inputs:

In[3]:=
ResourceFunction["FoldGraph"][Times, {2, 6}, {2, 3, 5}, VertexLabels -> Automatic]
Out[3]=

Fold a multi-output function:

In[4]:=
ResourceFunction["FoldGraph"][{#1 + #2, #1 #2} &, x, {a, b}, VertexLabels -> Automatic]
Out[4]=

Use arbitrary functions to define the vertices:

In[5]:=
ResourceFunction["FoldGraph"][Through@*{f, g}, x, {a, b}, VertexLabels -> Automatic]
Out[5]=

Tag edges:

In[6]:=
ResourceFunction[
 "FoldGraph"][{Labeled[#1 + #2, Row[{"+", #2}]], Labeled[#1 #2, Row[{"\[Times]", #2}]]} &, Range[4], VertexLabels -> Automatic, EdgeLabels -> "EdgeTag"]
Out[6]=

Use an operator form:

In[7]:=
ResourceFunction["FoldGraph"][Through@*{f, g}, VertexLabels -> Automatic] /@ {{a, b, c}, {1, 2, 3}}
Out[7]=

Options (1) 

TagHead (1) 

Use a different head to specify tags:

In[8]:=
ResourceFunction[
 "FoldGraph"][{#1 + #2 -> Style["+", 16, Red], #1 #2 -> Style["*", 16, Blue]} &, Range[4], EdgeLabels -> "EdgeTag", "TagHead" -> Rule]
Out[8]=

Version History

  • 1.0.0 – 02 August 2022

Related Resources

License Information