Skip to content

Instantly share code, notes, and snippets.

@jdh30
Created April 4, 2017 16:56
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 jdh30/512962cb29b96787c29964b2a7080db3 to your computer and use it in GitHub Desktop.
Save jdh30/512962cb29b96787c29964b2a7080db3 to your computer and use it in GitHub Desktop.
Imperative and purely functional depth-first searches in F#
open System.Collections.Generic
/// Imperative depth-first search
let dfs (V, E) =
let visited = HashSet(HashIdentity.Structural)
let stack = Stack[V]
while stack.Count > 0 do
let u = stack.Pop()
if not(visited.Contains u) then
for v in E u do
stack.Push v
visited.Add u
|> ignore
/// Functional depth-first search as a fold
let dfs f a (V, E) =
let rec loop visited a = function
| [] -> a
| u::us ->
if List.contains u visited then loop visited a us else
loop (u::us) (f a u) (E u @ us)
loop a V
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment