Functional Programming – Data Structures in Functional Programming

data structuresfunctional programminglisp

I'm currently playing with LISP (particularly Scheme and Clojure) and I'm wondering how typical data structures are dealt with in functional programming languages.

For example, let's say I would like to solve a problem using a graph pathfinding algorithm. How would one typically go about representing that graph in a functional programming language (primarily interested in pure functional style that can be applied to LISP)? Would I just forget about graphs altogether and solve the problem some other way?

Best Answer

It's been a while since I've worked in LISP, but as I recall, the basic non-atomic structure is a list. Everything else is based on that. So you could have a list of atoms where each atom is a node followed by a list of edges that connect the node to other nodes. I'm sure there's other ways to do it too.

Maybe something like this:

(
  (a (b c)),
  (b (a c)),
  (c (a b d)),
  (d (c))
)

could give a graph like this:

a<-->b<-->c<-->d
^         ^
|         |
+---------+

If you want to get fancy, you could add weights to it as well:

(
  (a (b 1.0 c 2.0)),
  (b (a 1.0 c 1.0)),
  (c (a 1.3 b 7.2 d 10.5)),
  (d (c -10.5))
)

You might also be interested in this: CL-Graph (found by google-searching the phrase "lisp graph structure" )

Related Topic