20-CS-4003-001 Organization of Programming Languages Fall 2018
Recursion

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures           Code

Topological Sort

```topo::Int -> [Int] -> [[Int]] -> [Int]
topo p deps x = y
where
dep = (deps !! 0)
depdeps = (x !! (dep-1))
remp = (removeall p x)
rempdep = (removeall dep remp)
y = if (deps == []) then [p]
else (topo dep depdeps rempdep) ++
(topo p (drop 1 deps) remp)
```
example:
```  let z = [[],[4],[2,4],[1]]::[[Int]]
topo 3 (z !! 2) z
[1,4,2,1,4,3]
```

Description of local variables:
 dep: dependency to explore depdeps: dependencies of that dependency remp: removed occurrences of p from graph rempdep: removed p and dep from graph

-  Performs a topological sort of elements beginning with element p. For convenience, elements are simply integers beginning with 1. There is a list of dependencies for each element. The inputs are as follows:

 x: a list of lists of numbers. The ith list is the dependency list for element i+1. Thus if x = [[3,6],[4,9],[2],...], the dependency list for element 1 is [3,6], for element 2 it is [4,9], for element 3 it is [2], and so on. It is convenient to think of the input as representing a directed graph where each element is a vertex and the element's dependency list gives the directed edges out of the corresponding vertex. p: a positive integer. The element from which the topological search is rooted. Starting the search from p may cause one or more elements to be missed. This eventuality is covered in topological which is given below. deps: the dependency list of p. Parameter deps is a list of integers which should be equal to (x !! (p-1)).

In the output list, no element should be to the left of one of its dependencies.

Warning: for convenience, no error checking is done, it is assumed that a topological sort exists for the given input

```topological::[[Int]] -> [[Int]]
topological x = y
where
y = [ topo i (x !! (i-1)) x |
i <- [1..length x] ]
```
example:
```let z = [[],[4],[2,4],[1]]::[[Int]]
remdups (flatten (topological z))
[1,4,2,3]
```
example:
```topological z
[[1],[1,4,2],[1,4,2,1,4,3],[1,4]]
```
-  Performs a topological sort of a given list of dependency lists x. Calls topo for every element to make sure all vertices of the graph are reached. Returns a list of lists, one list for each vertex. There typically are numerous duplicate elements among the lists but the leftmost duplicate is always the one that counts. The examples to the left show how to use topological and the results.