0

I have a graph that is implemented as a list of edges connecting arbitrary nodes, with the data types defined below.

type edge = int * int;;
type graph = edge list;;

How would I perform a purely functional depth-first search while avoiding getting stuck on a cycle? I am not quite sure of how to keep track of all the nodes visited while remaining purely functional. The answer is probably something trivial that I am not conceptually grasping for some reason.

Zhehao Chen
  • 217
  • 1
  • 10
  • 1
    See http://stackoverflow.com/a/4655846/69663 – so one way would be for your dfs function to return not only the maybe-found-value, but also the Set of nodes visited so far. – unhammer Oct 27 '15 at 08:26
  • You should check out https://hackage.haskell.org/package/fgl, it implements a very elegant way to work with graphs which I couldn't quite understand but seems to be similiar to zippers. – Niklas B. Oct 27 '15 at 18:07

1 Answers1

2

The search function has a parameter that tracks visited nodes. In FP one of the insights is that you can keep calling deeper and deeper (with tail calls). So you can pass the parameter along through all the calls, adding new nodes as you go.

Another parameter could be the nodes you plan to visit later. For DFS this would work like a stack.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108