11.07.2015 Views

Advanced Programming Guide

Advanced Programming Guide

Advanced Programming Guide

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

122 • Chapter 3: <strong>Programming</strong> with ModulesSecond Graph Constructor Here is another, different implementation ofthe Graph interface. The graph is represented by using a table N in whichthe neighbors of each vertex are stored.> Graph2 := proc()> local vertex_set, edge_set;> description "graph constructor";>> edge_set := { args };> vertex_set := map( op, edge_set );> if not andmap( type, edge_set, ’list’ ) then> error "graph must be specified by a sequence of edges"> end if;> if not andmap( edge -> evalb( nops ( edge )= 2), edge_set )> then> error "each edge must be specified "> "as a [ source, target ] pair"> end if;> module()> export order, size,> vertices, edges,> addedge;> local N, e, v, n, edge_pairs;> N := table();> edge_pairs := () -> { seq(> seq( [ v, n ], n = N[ v ] ),> v = map( op, { indices( N ) } )> ) };> vertices := () -> map( op, edge_pairs() );> edges := () -> map( Edge@op, edge_pairs() );> addedge := proc( src, targ )> if assigned( N[ src ] )> and not member( targ, N[ src ] ) then> N[ src ] := { op( N[ src ] ), targ }> else> N[ src ] := { targ };> end if;> NULL> end proc;> order := () -> nops( vertices() );> size := () -> nops( edges() );> for e in edge_set do> addedge( op( 1, e ), op( 2, e ) )> end do> end module> end proc:A graph returned by the constructor Graph2 also satisfies the Graph interface.> g2 := Graph2( [ a, b ], [ a, c ], [ b, c ] ):> type( g2, ’Graph’ );

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!