MALDA™ Reference Manual

The AI-First Programming Language - Version 1.0.11

14. Graphs

Graphs are data structures that represent relationships between nodes (vertices) connected by edges. MALDA supports both directed and undirected graphs with weighted edges and optional edge properties.

14.1 Graph Literals

Graphs are created with the graph directed { ... } or graph undirected { ... } literal syntax:

// Create a directed graph
var g = graph directed {
  nodes: ["A", "B", "C", "D"],
  edges: [
    { from: "A", to: "B", weight: 4 },
    { from: "A", to: "C", weight: 2 },
    { from: "B", to: "D", weight: 5 },
    { from: "C", to: "D", weight: 1 }
  ]
};

// Create an undirected graph
var g2 = graph undirected {
  nodes: ["X", "Y", "Z"],
  edges: [
    { from: "X", to: "Y", weight: 10 },
    { from: "Y", to: "Z", weight: 5 }
  ]
};

// Empty graph
var g3 = graph directed {};

14.2 Graph Operations

Graphs provide methods for manipulating nodes and edges:

var g = graph directed {};

// Add nodes
g.addNode("A");
g.addNode("B", "data");  // Optional node data

// Add edges
g.addEdge("A", "B", 5);  // from, to, weight
g.addEdge("A", "C", 3, dict { "label": "important" });  // with properties

// Query graph
print(g.hasNode("A"));        // true
print(g.hasEdge("A", "B"));   // true
print(g.getWeight("A", "B")); // 5
print(g.nodeCount());         // 2
print(g.edgeCount());         // 1
print(g.isDirected());        // true

// Get neighbors
var neighbors = g.getNeighbors("A");  // ["B", "C"]

// Get all nodes and edges
var nodes = g.nodes();   // ["A", "B", "C"]
var edges = g.edges();   // [[from, to, weight], ...]

// Remove nodes and edges
g.removeEdge("A", "B");
g.removeNode("C");

14.3 Graph Algorithms

Graphs support common graph algorithms:

var g = graph directed {
  nodes: ["A", "B", "C", "D"],
  edges: [
    { from: "A", to: "B", weight: 4 },
    { from: "A", to: "C", weight: 2 },
    { from: "B", to: "D", weight: 5 },
    { from: "C", to: "D", weight: 1 }
  ]
};

// Breadth-first search
var visited = g.bfs("A");  // ["A", "B", "C", "D"]
var pathResult = g.bfs("A", "D");  // { path: ["A", "B", "D"], found: true }

// Depth-first search
var dfsVisited = g.dfs("A");  // ["A", "B", "D", "C"]
var dfsPath = g.dfs("A", "D");  // { path: ["A", "B", "D"], found: true }

// Shortest path (Dijkstra's algorithm)
var shortest = g.shortestPath("A", "D");
print(shortest.path);     // ["A", "C", "D"]
print(shortest.distance); // 3
print(shortest.found);    // true

// Topological sort (directed graphs only)
var topo = g.topologicalSort();
print(topo.order);  // ["A", "B", "C", "D"] or ["A", "C", "B", "D"]
print(topo.valid);  // true

// Connected components
var components = g.connectedComponents();
// Returns array of arrays, each containing node IDs in a component

// Check for cycles
print(g.isCyclic());  // false

// Minimum spanning tree (undirected graphs only)
var gUndirected = graph undirected {
  nodes: ["A", "B", "C"],
  edges: [
    { from: "A", to: "B", weight: 1 },
    { from: "B", to: "C", weight: 2 },
    { from: "A", to: "C", weight: 4 }
  ]
};
var mst = gUndirected.minimumSpanningTree();
print(mst.edges);      // [[from, to, weight], ...]
print(mst.totalWeight); // 3

14.4 Graph Serialization

Graphs can be serialized to JSON format for storage or transmission, and deserialized to reconstruct the graph. The serialization format efficiently stores nodes once and references them by ID in edges, avoiding data duplication.

var g = graph directed {
  nodes: ["A", "B", "C"],
  edges: [
    { from: "A", to: "B", weight: 5 },
    { from: "B", to: "C", weight: 3 }
  ]
};

// Serialize to JSON string
var json = g.serialize();
print(json);

// Serialize directly to file
g.serialize("graph.json");

// Deserialize from JSON string
var g2 = g.deserialize(json);

// Deserialize from file
var g3 = g.deserialize("graph.json");

// Verify the deserialized graph
print(g2.nodeCount());  // 3
print(g2.edgeCount());  // 2
print(g2.hasEdge("A", "B"));  // true

Serialization Format:

The JSON format stores graphs efficiently:

{
  "isDirected": true,
  "nodes": [
    { "id": "A", "data": null },
    { "id": "B", "data": "node data" }
  ],
  "edges": [
    { "from": "A", "to": "B", "weight": 5.0, "properties": null }
  ]
}

Node Data and Edge Properties:

Node data and edge properties are fully preserved during serialization:

var g = graph directed {};
g.addNode("A", "important data");
g.addNode("B", 42);
g.addEdge("A", "B", 5, dict { "label": "primary", "type": "connection" });

var json = g.serialize();
var g2 = g.deserialize(json);

print(g2.getNode("A"));  // "important data"
print(g2.getNode("B"));  // 42
// Edge properties are preserved internally

Undirected Graphs:

For undirected graphs, edges are stored once in the serialized format, and reverse edges are automatically created during deserialization:

var g1 = graph undirected {
  nodes: ["X", "Y"],
  edges: [
    { from: "X", to: "Y", weight: 10 }
  ]
};

var json = g1.serialize();
var g2 = g1.deserialize(json);

// Both directions work after deserialization
print(g2.hasEdge("X", "Y"));  // true
print(g2.hasEdge("Y", "X"));  // true

14.5 Graph Methods Reference

14.6 Graph Applications

Graphs are versatile data structures with many practical applications. Here are common use cases organized by category:

Pathfinding & Routing

1. Route Planning & Navigation

Find optimal routes between locations using shortest path algorithms. Edge weights can represent distance, time, or cost.

var roadNetwork = graph directed {
  nodes: ["Home", "Work", "Store", "Park"],
  edges: [
    { from: "Home", to: "Work", weight: 15 },
    { from: "Home", to: "Store", weight: 5 },
    { from: "Store", to: "Work", weight: 12 }
  ]
};
var route = roadNetwork.shortestPath("Home", "Work");
print("Optimal route: " + route.path);
print("Total distance: " + route.distance);

2. Supply Chain & Logistics Optimization

Optimize shipping routes and minimize delivery time or transportation costs in supply chain networks.

var supplyChain = graph directed {
  nodes: ["Factory", "Warehouse1", "Warehouse2", "Retailer"],
  edges: [
    { from: "Factory", to: "Warehouse1", weight: 50 },
    { from: "Factory", to: "Warehouse2", weight: 60 },
    { from: "Warehouse1", to: "Retailer", weight: 20 },
    { from: "Warehouse2", to: "Retailer", weight: 15 }
  ]
};
var optimalRoute = supplyChain.shortestPath("Factory", "Retailer");

Dependency Management

3. Task Dependency Management

Determine the correct execution order for tasks with dependencies using topological sorting. Useful for build systems, course prerequisites, and project planning.

var buildGraph = graph directed {
  nodes: ["compile", "test", "package", "deploy"],
  edges: [
    { from: "compile", to: "test", weight: 1 },
    { from: "test", to: "package", weight: 1 },
    { from: "package", to: "deploy", weight: 1 }
  ]
};
var buildOrder = buildGraph.topologicalSort();
if (buildOrder.valid) {
  print("Build order: " + buildOrder.order);
}

4. Compiler Dependency Resolution

Determine compilation order for modules and detect circular dependencies that would prevent compilation.

var moduleDeps = graph directed {
  nodes: ["utils", "parser", "lexer", "compiler"],
  edges: [
    { from: "lexer", to: "parser", weight: 1 },
    { from: "parser", to: "compiler", weight: 1 },
    { from: "utils", to: "parser", weight: 1 }
  ]
};
if (!moduleDeps.isCyclic()) {
  var buildOrder = moduleDeps.topologicalSort();
  print("Compilation order: " + buildOrder.order);
} else {
  print("Circular dependency detected!");
}

Network Analysis

5. Social Network Analysis

Identify friend groups, analyze influence spread, and find shortest connection paths between individuals.

var socialNetwork = graph undirected {
  nodes: ["Alice", "Bob", "Charlie", "Diana", "Eve"],
  edges: [
    { from: "Alice", to: "Bob", weight: 1 },
    { from: "Bob", to: "Charlie", weight: 1 },
    { from: "Diana", to: "Eve", weight: 1 }
  ]
};
var groups = socialNetwork.connectedComponents();
print("Friend groups: " + groups);
var connectionPath = socialNetwork.bfs("Alice", "Charlie");

6. Network Infrastructure Planning

Design cost-effective networks (cable, fiber, roads) that connect all nodes with minimum total cost using minimum spanning trees.

var cityNetwork = graph undirected {
  nodes: ["CityA", "CityB", "CityC", "CityD"],
  edges: [
    { from: "CityA", to: "CityB", weight: 100 },
    { from: "CityB", to: "CityC", weight: 150 },
    { from: "CityA", to: "CityC", weight: 200 },
    { from: "CityC", to: "CityD", weight: 80 }
  ]
};
var mst = cityNetwork.minimumSpanningTree();
print("Optimal network edges: " + mst.edges);
print("Total cost: " + mst.totalWeight);

7. Power Grid & Electrical Network Analysis

Design efficient power distribution networks and identify isolated grid components.

var powerGrid = graph undirected {
  nodes: ["PowerPlant", "Substation1", "Substation2", "CityA"],
  edges: [
    { from: "PowerPlant", to: "Substation1", weight: 100 },
    { from: "Substation1", to: "CityA", weight: 50 },
    { from: "Substation1", to: "Substation2", weight: 80 }
  ]
};
var efficientGrid = powerGrid.minimumSpanningTree();
var gridComponents = powerGrid.connectedComponents();

Relationship Modeling

8. Workflow & Process Modeling

Model workflows, detect potential deadlocks, and validate process flows by checking for cycles.

var workflow = graph directed {
  nodes: ["start", "process", "validate", "end"],
  edges: [
    { from: "start", to: "process", weight: 1 },
    { from: "process", to: "validate", weight: 1 },
    { from: "validate", to: "end", weight: 1 }
  ]
};
if (workflow.isCyclic()) {
  print("Workflow has cycles - potential deadlock!");
} else {
  print("Workflow is valid");
}

9. Organizational Hierarchy & Reporting Structure

Model company structure, find reporting chains, and identify management levels using breadth-first search.

var orgChart = graph directed {
  nodes: ["CEO", "VP1", "VP2", "Manager1", "Employee1"],
  edges: [
    { from: "CEO", to: "VP1", weight: 1 },
    { from: "CEO", to: "VP2", weight: 1 },
    { from: "VP1", to: "Manager1", weight: 1 },
    { from: "Manager1", to: "Employee1", weight: 1 }
  ]
};
var reportingChain = orgChart.bfs("CEO", "Employee1");
print("Reporting chain: " + reportingChain.path);

11. Recommendation Systems

Find similar items, related products, or content recommendations by exploring neighbor relationships.

var productGraph = graph undirected {
  nodes: ["ProductA", "ProductB", "ProductC", "ProductD"],
  edges: [
    { from: "ProductA", to: "ProductB", weight: 0.9 },
    { from: "ProductB", to: "ProductC", weight: 0.7 },
    { from: "ProductC", to: "ProductD", weight: 0.5 }
  ]
};
var recommendations = productGraph.getNeighbors("ProductA");
print("Recommended products: " + recommendations);
var relatedCluster = productGraph.bfs("ProductA");

See Also