Next: Cartesian
Up: Programming Concepts
Previous: Lookup
  Contents
  Index
Subsections
Description
This concept takes a list of entries with indices I and J and a value V, and put the value in a matrix M at position Mi,j.
- L
- a list of entries
- Matrix
- a matrix
:-mode fill_matrix(+,+).
fill_matrix(L,Matrix):-
(foreach(entry with [i:I,j:J,value:V],L),
param(Matrix) do
subscript(Matrix,[I,J],V)
).
The program may fail if two entries in the list refer to the same index pair I and J, as the program would then try to insert two values at the same position.
It is not required that the input list contains all index combinations, we can use the iteration on array concept to fill any un-set elements with a default value.
The example fills an array PMatrix with values from a list of hop/3 terms. We also convert the node names in the hop term into node indices for lookup in the PMatrix matrix.
:-mode fill_with_hops(+,+,+).
fill_with_hops([],_,_).
fill_with_hops([hop(Source,Dest,List)|R],Nodes,PMatrix):-
find_node_index(Source,Nodes,S),
find_node_index(Dest,Nodes,D),
find_node_indices(List,Nodes,L),
length(L,N),
subscript(PMatrix,[S,D],pi_entry with [list:L,
length:N]),
fill_with_hops(R,Nodes,PMatrix).
Warwick Harvey
2004-08-07