Skip to content

Instantly share code, notes, and snippets.

@thelissimus
Created July 28, 2025 05:29
Show Gist options
  • Select an option

  • Save thelissimus/bd7a590b4c379b0a0a37d84aa494f51f to your computer and use it in GitHub Desktop.

Select an option

Save thelissimus/bd7a590b4c379b0a0a37d84aa494f51f to your computer and use it in GitHub Desktop.
data Graph a
= Empty
| Vertex a
| Overlay (Graph a) (Graph a)
| Connect (Graph a) (Graph a)
deriving stock (Show)
instance (Num a) => Num (Graph a) where
fromInteger = Vertex . fromInteger
(+) = Overlay
(*) = Connect
signum = const Empty
abs = id
negate = id
instance Semigroup (Graph a) where
(<>) = Overlay
instance Monoid (Graph a) where
mempty = Empty
vertices :: [a] -> Graph a
vertices = foldr (Overlay . Vertex) Empty
edges :: [(a, a)] -> Graph a
edges = foldr (\(x, y) acc -> Overlay (Connect (Vertex x) (Vertex y)) acc) Empty
create :: [a] -> [(a, a)] -> Graph a
create v e = Overlay (vertices v) (edges e)
foldg :: b -> (a -> b) -> (b -> b -> b) -> (b -> b -> b) -> Graph a -> b
foldg e v o c = go
where
go = \case
Empty -> e
Vertex x -> v x
Overlay x y -> o (go x) (go y)
Connect x y -> c (go x) (go y)
transpose :: Graph a -> Graph a
transpose = foldg Empty Vertex Overlay (flip Connect)
induce :: (a -> Bool) -> Graph a -> Graph a
induce f = foldg Empty (\x -> if f x then Vertex x else Empty) Overlay Connect
removeVertex :: (Eq a) => a -> Graph a -> Graph a
removeVertex = induce . (/=)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment