Created
November 9, 2023 09:51
-
-
Save arialdomartini/067697d10f1bb5f948d3a38c796f7c3a to your computer and use it in GitHub Desktop.
hasPath.hs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
which can be made shorter with