Write Haskell code for topological sort
- User
Write Haskell code for topological sort
Assistant
Topological sort in Haskell can be implemented using graph data structures and depth-first search (DFS). Here is an example:
-- Represent a directed graph using an adjacency list type Graph = [(Int, [Int])] -- Perform depth-first search with topological sort topologicalSort :: Graph -> [Int] topologicalSort graph = map fst . filter (not . null) . reverse . group . sortBy (flip compare `on` snd) . concat $ dfs graph [] 0 -- Depth-first search with topological sort dfs :: Graph -> [Int] -> Int -> [(Int, [Int])] dfs visitedNodes currNodes startNode = let (neighbors, graph') = (filter (\(x,_) -> not (x `elem` visitedNodes)) . concat $ map (graphNodeNeighbors startNode) (graph ++ [(startNode, [])]) , map (\(x, y) -> if x == startNode then (x, drop (length currNodes) y) else (x, y)) graph) in (currNodes ++ map fst neighbors, neighbors ++ graph') where graphNodeNeighbors node graph = [(n, es) | (n, es) <- graph, n /= node]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.