Sure! Here's an example of how you can implement topological sort in Haskell:
import Data.List
import Data.Maybe
type Node = Int
type Edge = (Node, Node)
type Graph = [Edge]
-- | Topological sort algorithm
topologicalSort :: Graph -> Maybe [Node]
topologicalSort graph = reverse <$> dfs [] graph
-- | Depth-first search with cycle detection
dfs :: [Node] -> Graph -> Maybe [Node]
dfs visited [] = Just visited
dfs visited graph
| isCycle visited graph = Nothing
| otherwise = listToMaybe $ catMaybes [dfs (node:visited) (delete (node, _) graph) | node <- sources graph]
-- | Check if there is a cycle in the graph
isCycle :: [Node] -> Graph -> Bool
isCycle visited graph = any (\(node, _) -> node `elem` visited) graph
-- | Find nodes that have no incoming edges
sources :: Graph -> [Node]
sources graph = nub $ map snd graph \\ map fst graph
-- | Example usage
main :: IO ()
main = do
let graph = [(1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (4, 5)]
case topologicalSort graph of
Just sorted -> print sorted
Nothing -> putStrLn "Graph contains a cycle"
In this implementation, we represent a directed graph using a list of edges. Each edge is a pair of nodes, where the first node is the source and the second node is the destination.
The topologicalSort function takes a graph as input and returns a Maybe list of nodes representing the topologically sorted order. If the graph contains a cycle, it returns Nothing.
The dfs function performs a depth-first search on the graph, keeping track of the visited nodes. If a cycle is detected, it returns Nothing. Otherwise, it recursively explores the graph by removing the current node and its outgoing edges from the graph, and continues the search from the next source node.
The isCycle function checks if there is a cycle in the graph by checking if any of the outgoing edges from the current node have already been visited.
The sources function finds all nodes that have no incoming edges by taking the set difference between the list of destination nodes and the list of source nodes.
Finally, in the main function, we define an example graph and call topologicalSort on it. If the sort is successful, we print the sorted order, otherwise we print a message indicating that the graph contains a cycle.