A topological ordering of a DAG, author David Eppstein at Wikipedia (CC0 1.0)

Code Snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env stack
{- stack
   --resolver lts-12.0
   --install-ghc
   script
   --ghc-options -Werror
   --ghc-options -Wall
   --
-}

--------------------------------------------------------------------------------

{-# LANGUAGE Safe #-}

--------------------------------------------------------------------------------

module Main (main) where

--------------------------------------------------------------------------------

import           Control.Arrow
  ( first
  )
import           Data.Bits
  ( xor
  , (.&.)
  )
import           Data.List
  ( sort
  )
import           Data.Maybe
  ( catMaybes
  )

--------------------------------------------------------------------------------

newtype Vertices a =
  V (Map Integer a)

newtype Edges =
  E (Map Integer [Integer])

data DAG a = G (Vertices a) Edges

--------------------------------------------------------------------------------

-- F U N C T I O N A L  P E A R L S
-- Red-Black Trees in a Functional Setting
--
-- CHRIS OKASAKI
-- School of Computer Science, Carnegie Mellon University
-- 5000 Forbes Avenue, Pittsburgh, Pennsylvania, USA 15213
-- (e-mail: [email protected])

-- Red-Black Trees
data Color  = R | B
data Tree a = L | T Color (Tree a) a (Tree a)

instance Show Color where
  show R = "Red"
  show B = "Black"

instance Show a => Show (Tree a) where
  show = aux 0
    where
      aux l  L            =
        replicate l ' ' ++ "nil"
      aux l (T c lt x rt) =
        replicate l ' ' ++ show c ++ ": " ++ show x ++ "\n" ++
        replicate n ' ' ++ aux  n lt                ++ "\n" ++
        replicate n ' ' ++ aux  n rt
        where
          n = l + 1

-- Simple Map Operations
type Map k a = Tree (k, a)

empty :: Map k a
empty = L

member :: Ord k => k -> Map k a -> Maybe a
member _  L = Nothing
member k (T _ a (k', y) b)
  | k <  k' = member k a
  | k == k' = Just y
  | k >  k' = member k b
member _ (T _ _ (_,  _) _) = Nothing

insert :: Ord k => k -> a -> Map k a -> Map k a
insert k v m =
  blk . aux $ m
  where
    blk (T _ a y b) = T B a y b
    blk ___________ = error "Shouldn't be possible (insert -> blk)"
    aux  L = T R L (k,v) L
    aux (T c a y@(k', _) b)
      | k <  k' = bal c (aux a) y      b
      | k == k' = T   c      a  y      b
      | k >  k' = bal c      a  y (aux b)
    aux ___________ = error "Shouldn't be possible (insert -> aux)"
    bal B (T R (T R a x b) y c) z d = T R (T B a x b) y (T B c z d)
    bal B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d)
    bal B a x (T R (T R b y c) z d) = T R (T B a x b) y (T B c z d)
    bal B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d)
    bal c a x b                     = T c a x b

toList :: Map k a -> [(k, a)]
toList  L          = [                         ]
toList (T _ a x b) = toList a ++ [x] ++ toList b

--------------------------------------------------------------------------------

-- FNV Hash
--
-- http://isthe.com/chongo/tech/comp/fnv/#FNV-1a

fnv1a :: (Show a) => a -> Integer
fnv1a =
  foldl ( \ a x -> ((a `xor` x) * prm) .&. bin) off . aux . show
  where
    aux = map (fromIntegral . fromEnum)
    prm = 309485009821345068724781371
    off = 144066263297769815596495629667062367629
    bin = 340282366920938463463374607431768211455

--------------------------------------------------------------------------------

cartProd :: [a] -> [b] -> [(a, b)]
cartProd xs ys =
  (,) <$> xs <*> ys

vertices :: Ord a => DAG a -> [a]
vertices (G (V vs) _) =
  sort $ map snd $ toList vs

edges :: Ord a => DAG a -> [(a, a)]
edges (G (V vs) (E es)) =
  reverse $
  sort    $
  concat  $
  map (uncurry cartProd) $
  map (first (:[]))      $
  zip fs tss
  where
    (xs,ys) = unzip $ toList es
    fs  =     catMaybes $ map       (flip member vs) xs
    tss = map catMaybes $ map (map $ flip member vs) ys

new :: (Show a) => a -> DAG a
new v =
  G (V $ insert hsv v empty) (E empty)
  where
    hsv = fnv1a v

add :: (Eq a, Show a) => [a] -> a -> DAG a -> Either String (DAG a)
add ps v (G (V vs) (E es)) =
  case member hsv vs of
    Just  _ -> Left "Vertex, is already in the graph"
    Nothing ->
      if all (/= Nothing) $ map (flip member vs) hsps
      then
        Right $ G
        (V $ insert hsv v vs)
        (E $ foldl ( \ a ph -> insert hsv ph a) es [ hsps ])
      else
        Left "One of the parent vertices, doesn't exist"
  where
    hsps = map fnv1a ps
    hsv  =     fnv1a v

--------------------------------------------------------------------------------

main :: IO ()
main =
  putStrLn "# Example 1 (single neighbor): " >>
  (
    case dag1 of
      Left msg -> putStrLn msg
      Right  g ->
        (putStrLn $ "vertices: " ++ (show $ vertices g)) >>
        (putStrLn $ "edges:    " ++ (show $ edges    g))
  ) >>
  putStrLn "" >>
  putStrLn "# Example 2 (multiple neighbors, Wikipedia diagram): " >>
  (
    case dag2 of
      Left msg -> putStrLn msg
      Right  g ->
        (putStrLn $ "vertices: " ++ (show $ vertices g)) >>
        (putStrLn $ "edges:    " ++ (show $ edges    g))
  )
  where
    dag1 =
      foldl (\ g (p,v) -> g >>= add p v) x xs
      where
        x  = Right $ new 1
        xs = take 10 $ zip (map (:[]) nat) $ drop 1 nat
    nat = 1 : map (+ 1) nat :: [ Integer ]
    dag2 =
      -- DAG example from Wikipedia:
      -- https://en.wikipedia.org/wiki/File:Topological_Ordering.svg
      (Right $ new 'a')
      >>= add ['a']     'b' >>= add ['b'] 'c' >>= add ['a']     'd'
      >>= add ['d']     'e' >>= add ['d'] 'f' >>= add ['b','f'] 'g'
      >>= add ['e','g'] 'h'

Code Output:

# Example 1 (single neighbor): 
vertices: [1,2,3,4,5,6,7,8,9,10,11]
edges:    [(11,10),(10,9),(9,8),(8,7),(7,6),(6,5),(5,4),(4,3),(3,2),(2,1)]

# Example 2 (multiple neighbors, Wikipedia diagram): 
vertices: "abcdefgh"
edges:    [('h','g'),('h','e'),('g','f'),('g','b'),('f','d'),('e','d'),('d','a')
          ,('c','b'),('b','a')
          ]

References: