title: Finding distance between nodes of a graph in prolog
body: <p>I have a graph in Prolog represented by the edges &amp; weights:</p>
  
  <pre><code>connected(a,b,2).
  connected(b,e,1).
  connected(b,l,5).
  connected(b,g,2).
  connected(c,s,2).
  connected(d,a,2).
  connected(d,k,4).
  connected(d,l,7).
  connected(e,m,2).
  </code></pre>
  
  <p>I need to write a predicate which takes a list of nodes &amp; distance.</p>
  
  <pre><code>?- dist([a,b,e],X).
  X=3
  </code></pre>
  
  <p>I've tried to write it, but it is very clumsy &amp; doesn't give the intended result. </p>
  
  <p>The basic idea I have is:
  If it is a list of 2 elements then see if they are connected. 
  If more then 2 elements in the list: see if the 1st element &amp; 2nd element are connected,
  recursively see if the next elements are connected.
  I have defined 2 auxiliary predicates for head &amp; tail.</p>
  
  <pre><code>dist([A, B], X) :-
      connected(A, B, X).
  dist([A|B], Length) :-
      connected(A, hd(B,H,N), X),  % sees if A &amp; next element in the list are connected
      dist(tl(B,H,N), Length1),    % recursive call with the list excluding element A
      Length is X + Length1.       
  
  hd([H|T],H,Q).
  tl([H|T],T,Q).
  </code></pre>
  
  <p>I am very new to Prolog land and I am still trying to comprehend the language semantics.
  Please suggest an efficient way to go about this problem.</p>