Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created November 9, 2023 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arialdomartini/067697d10f1bb5f948d3a38c796f7c3a to your computer and use it in GitHub Desktop.
Save arialdomartini/067697d10f1bb5f948d3a38c796f7c3a to your computer and use it in GitHub Desktop.
hasPath.hs
module Main where
type Point = Int
type From = Point
type To = Point
type Segment = (From, To)
type Graph = [Segment]
hasPath :: Graph -> From -> To -> Bool
hasPath [] _ _ = False
hasPath graph from to =
any (\(f, t) -> (f,t) == (from, to)) graph
||
let tos = graph `continueFrom` from in
or $ fmap (\newFrom -> hasPath (graph `withoutFrom` from) newFrom to) tos
withoutFrom :: Graph -> From -> Graph
withoutFrom graph from = filter (\(f,_) -> f /= from) graph
continueFrom :: Graph -> From -> [To]
graph `continueFrom` node =
map snd $ filter (\(f, t) -> f == node) graph
main = do
putStrLn $ show (hasPath [(1,2), (2,3), (3,4)] 1 4)
@arialdomartini
Copy link
Author

arialdomartini commented Nov 9, 2023

which can be made shorter with

hasPath :: Graph -> From -> To -> Bool
hasPath [] _ _ = False
hasPath graph from to =
  any (\(f, t) -> (f,t) == (from, to)) graph
  ||
  any ((\newFrom -> hasPath graph newFrom to) . snd) (filter (\(f, _) -> f == from) graph)

@arialdomartini
Copy link
Author

arialdomartini commented Nov 9, 2023

Alternative:

hasPath' :: Graph -> From -> To -> Bool
hasPath' graph from to
    | from == to = True
    | otherwise = or $ fmap (\next -> hasPath' graph next to) ((map snd (filter (\(f, _) -> f == from) graph)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment