1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
|
#----------------------------------------------------------------------
#
# list.tcl --
#
# Definitions for extended processing of Tcl lists.
#
# Copyright (c) 2003 by Kevin B. Kenny. All rights reserved.
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# RCS: @(#) $Id: list.tcl,v 1.27 2011/09/17 14:35:36 mic42 Exp $
#
#----------------------------------------------------------------------
package require Tcl 8.4
package require cmdline
namespace eval ::struct { namespace eval list {} }
namespace eval ::struct::list {
namespace export list
if {0} {
# Possibly in the future.
namespace export Lassign
namespace export LdbJoin
namespace export LdbJoinOuter
namespace export Ldelete
namespace export Lequal
namespace export Lfilter
namespace export Lfilterfor
namespace export Lfirstperm
namespace export Lflatten
namespace export Lfold
namespace export Lforeachperm
namespace export Liota
namespace export LlcsInvert
namespace export LlcsInvert2
namespace export LlcsInvertMerge
namespace export LlcsInvertMerge2
namespace export LlongestCommonSubsequence
namespace export LlongestCommonSubsequence2
namespace export Lmap
namespace export Lmapfor
namespace export Lnextperm
namespace export Lpermutations
namespace export Lrepeat
namespace export Lrepeatn
namespace export Lreverse
namespace export Lshift
namespace export Lswap
namespace export Lshuffle
}
}
##########################
# Public functions
# ::struct::list::list --
#
# Command that access all list commands.
#
# Arguments:
# cmd Name of the subcommand to dispatch to.
# args Arguments for the subcommand.
#
# Results:
# Whatever the result of the subcommand is.
proc ::struct::list::list {cmd args} {
# Do minimal args checks here
if { [llength [info level 0]] == 1 } {
return -code error "wrong # args: should be \"$cmd ?arg arg ...?\""
}
set sub L$cmd
if { [llength [info commands ::struct::list::$sub]] == 0 } {
set optlist [info commands ::struct::list::L*]
set xlist {}
foreach p $optlist {
lappend xlist [string range $p 1 end]
}
return -code error \
"bad option \"$cmd\": must be [linsert [join $xlist ", "] "end-1" "or"]"
}
return [uplevel 1 [linsert $args 0 ::struct::list::$sub]]
}
##########################
# Private functions follow
proc ::struct::list::K { x y } { set x }
##########################
# Implementations of the functionality.
#
# ::struct::list::LlongestCommonSubsequence --
#
# Computes the longest common subsequence of two lists.
#
# Parameters:
# sequence1, sequence2 -- Two lists to compare.
# maxOccurs -- If provided, causes the procedure to ignore
# lines that appear more than $maxOccurs times
# in the second sequence. See below for a discussion.
# Results:
# Returns a list of two lists of equal length.
# The first sublist is of indices into sequence1, and the
# second sublist is of indices into sequence2. Each corresponding
# pair of indices corresponds to equal elements in the sequences;
# the sequence returned is the longest possible.
#
# Side effects:
# None.
#
# Notes:
#
# While this procedure is quite rapid for many tasks of file
# comparison, its performance degrades severely if the second list
# contains many equal elements (as, for instance, when using this
# procedure to compare two files, a quarter of whose lines are blank.
# This drawback is intrinsic to the algorithm used (see the References
# for details). One approach to dealing with this problem that is
# sometimes effective in practice is arbitrarily to exclude elements
# that appear more than a certain number of times. This number is
# provided as the 'maxOccurs' parameter. If frequent lines are
# excluded in this manner, they will not appear in the common subsequence
# that is computed; the result will be the longest common subsequence
# of infrequent elements.
#
# The procedure struct::list::LongestCommonSubsequence2
# functions as a wrapper around this procedure; it computes the longest
# common subsequence of infrequent elements, and then subdivides the
# subsequences that lie between the matches to approximate the true
# longest common subsequence.
#
# References:
# J. W. Hunt and M. D. McIlroy, "An algorithm for differential
# file comparison," Comp. Sci. Tech. Rep. #41, Bell Telephone
# Laboratories (1976). Available on the Web at the second
# author's personal site: http://www.cs.dartmouth.edu/~doug/
proc ::struct::list::LlongestCommonSubsequence {
sequence1
sequence2
{maxOccurs 0x7fffffff}
} {
# Construct a set of equivalence classes of lines in file 2
set index 0
foreach string $sequence2 {
lappend eqv($string) $index
incr index
}
# K holds descriptions of the common subsequences.
# Initially, there is one common subsequence of length 0,
# with a fence saying that it includes line -1 of both files.
# The maximum subsequence length is 0; position 0 of
# K holds a fence carrying the line following the end
# of both files.
lappend K [::list -1 -1 {}]
lappend K [::list [llength $sequence1] [llength $sequence2] {}]
set k 0
# Walk through the first file, letting i be the index of the line and
# string be the line itself.
set i 0
foreach string $sequence1 {
# Consider each possible corresponding index j in the second file.
if { [info exists eqv($string)]
&& [llength $eqv($string)] <= $maxOccurs } {
# c is the candidate match most recently found, and r is the
# length of the corresponding subsequence.
set r 0
set c [lindex $K 0]
foreach j $eqv($string) {
# Perform a binary search to find a candidate common
# subsequence to which may be appended this match.
set max $k
set min $r
set s [expr { $k + 1 }]
while { $max >= $min } {
set mid [expr { ( $max + $min ) / 2 }]
set bmid [lindex [lindex $K $mid] 1]
if { $j == $bmid } {
break
} elseif { $j < $bmid } {
set max [expr {$mid - 1}]
} else {
set s $mid
set min [expr { $mid + 1 }]
}
}
# Go to the next match point if there is no suitable
# candidate.
if { $j == [lindex [lindex $K $mid] 1] || $s > $k} {
continue
}
# s is the sequence length of the longest sequence
# to which this match point may be appended. Make
# a new candidate match and store the old one in K
# Set r to the length of the new candidate match.
set newc [::list $i $j [lindex $K $s]]
if { $r >= 0 } {
lset K $r $c
}
set c $newc
set r [expr { $s + 1 }]
# If we've extended the length of the longest match,
# we're done; move the fence.
if { $s >= $k } {
lappend K [lindex $K end]
incr k
break
}
}
# Put the last candidate into the array
lset K $r $c
}
incr i
}
# Package the common subsequence in a convenient form
set seta {}
set setb {}
set q [lindex $K $k]
for { set i 0 } { $i < $k } {incr i } {
lappend seta {}
lappend setb {}
}
while { [lindex $q 0] >= 0 } {
incr k -1
lset seta $k [lindex $q 0]
lset setb $k [lindex $q 1]
set q [lindex $q 2]
}
return [::list $seta $setb]
}
# ::struct::list::LlongestCommonSubsequence2 --
#
# Derives an approximation to the longest common subsequence
# of two lists.
#
# Parameters:
# sequence1, sequence2 - Lists to be compared
# maxOccurs - Parameter for imprecise matching - see below.
#
# Results:
# Returns a list of two lists of equal length.
# The first sublist is of indices into sequence1, and the
# second sublist is of indices into sequence2. Each corresponding
# pair of indices corresponds to equal elements in the sequences;
# the sequence returned is an approximation to the longest possible.
#
# Side effects:
# None.
#
# Notes:
# This procedure acts as a wrapper around the companion procedure
# struct::list::LongestCommonSubsequence and accepts the same
# parameters. It first computes the longest common subsequence of
# elements that occur no more than $maxOccurs times in the
# second list. Using that subsequence to align the two lists,
# it then tries to augment the subsequence by computing the true
# longest common subsequences of the sublists between matched pairs.
proc ::struct::list::LlongestCommonSubsequence2 {
sequence1
sequence2
{maxOccurs 0x7fffffff}
} {
# Derive the longest common subsequence of elements that occur at
# most $maxOccurs times
foreach { l1 l2 } \
[LlongestCommonSubsequence $sequence1 $sequence2 $maxOccurs] {
break
}
# Walk through the match points in the sequence just derived.
set result1 {}
set result2 {}
set n1 0
set n2 0
foreach i1 $l1 i2 $l2 {
if { $i1 != $n1 && $i2 != $n2 } {
# The match points indicate that there are unmatched
# elements lying between them in both input sequences.
# Extract the unmatched elements and perform precise
# longest-common-subsequence analysis on them.
set subl1 [lrange $sequence1 $n1 [expr { $i1 - 1 }]]
set subl2 [lrange $sequence2 $n2 [expr { $i2 - 1 }]]
foreach { m1 m2 } [LlongestCommonSubsequence $subl1 $subl2] break
foreach j1 $m1 j2 $m2 {
lappend result1 [expr { $j1 + $n1 }]
lappend result2 [expr { $j2 + $n2 }]
}
}
# Add the current match point to the result
lappend result1 $i1
lappend result2 $i2
set n1 [expr { $i1 + 1 }]
set n2 [expr { $i2 + 1 }]
}
# If there are unmatched elements after the last match in both files,
# perform precise longest-common-subsequence matching on them and
# add the result to our return.
if { $n1 < [llength $sequence1] && $n2 < [llength $sequence2] } {
set subl1 [lrange $sequence1 $n1 end]
set subl2 [lrange $sequence2 $n2 end]
foreach { m1 m2 } [LlongestCommonSubsequence $subl1 $subl2] break
foreach j1 $m1 j2 $m2 {
lappend result1 [expr { $j1 + $n1 }]
lappend result2 [expr { $j2 + $n2 }]
}
}
return [::list $result1 $result2]
}
# ::struct::list::LlcsInvert --
#
# Takes the data describing a longest common subsequence of two
# lists and inverts the information in the sense that the result
# of this command will describe the differences between the two
# sequences instead of the identical parts.
#
# Parameters:
# lcsData longest common subsequence of two lists as
# returned by longestCommonSubsequence(2).
# Results:
# Returns a single list whose elements describe the differences
# between the original two sequences. Each element describes
# one difference through three pieces, the type of the change,
# a pair of indices in the first sequence and a pair of indices
# into the second sequence, in this order.
#
# Side effects:
# None.
proc ::struct::list::LlcsInvert {lcsData len1 len2} {
return [LlcsInvert2 [::lindex $lcsData 0] [::lindex $lcsData 1] $len1 $len2]
}
proc ::struct::list::LlcsInvert2 {idx1 idx2 len1 len2} {
set result {}
set last1 -1
set last2 -1
foreach a $idx1 b $idx2 {
# Four possible cases.
# a) last1 ... a and last2 ... b are not empty.
# This is a 'change'.
# b) last1 ... a is empty, last2 ... b is not.
# This is an 'addition'.
# c) last1 ... a is not empty, last2 ... b is empty.
# This is a deletion.
# d) If both ranges are empty we can ignore the
# two current indices.
set empty1 [expr {($a - $last1) <= 1}]
set empty2 [expr {($b - $last2) <= 1}]
if {$empty1 && $empty2} {
# Case (d), ignore the indices
} elseif {$empty1} {
# Case (b), 'addition'.
incr last2 ; incr b -1
lappend result [::list added [::list $last1 $a] [::list $last2 $b]]
incr b
} elseif {$empty2} {
# Case (c), 'deletion'
incr last1 ; incr a -1
lappend result [::list deleted [::list $last1 $a] [::list $last2 $b]]
incr a
} else {
# Case (q), 'change'.
incr last1 ; incr a -1
incr last2 ; incr b -1
lappend result [::list changed [::list $last1 $a] [::list $last2 $b]]
incr a
incr b
}
set last1 $a
set last2 $b
}
# Handle the last chunk, using the information about the length of
# the original sequences.
set empty1 [expr {($len1 - $last1) <= 1}]
set empty2 [expr {($len2 - $last2) <= 1}]
if {$empty1 && $empty2} {
# Case (d), ignore the indices
} elseif {$empty1} {
# Case (b), 'addition'.
incr last2 ; incr len2 -1
lappend result [::list added [::list $last1 $len1] [::list $last2 $len2]]
} elseif {$empty2} {
# Case (c), 'deletion'
incr last1 ; incr len1 -1
lappend result [::list deleted [::list $last1 $len1] [::list $last2 $len2]]
} else {
# Case (q), 'change'.
incr last1 ; incr len1 -1
incr last2 ; incr len2 -1
lappend result [::list changed [::list $last1 $len1] [::list $last2 $len2]]
}
return $result
}
proc ::struct::list::LlcsInvertMerge {lcsData len1 len2} {
return [LlcsInvertMerge2 [::lindex $lcsData 0] [::lindex $lcsData 1] $len1 $len2]
}
proc ::struct::list::LlcsInvertMerge2 {idx1 idx2 len1 len2} {
set result {}
set last1 -1
set last2 -1
foreach a $idx1 b $idx2 {
# Four possible cases.
# a) last1 ... a and last2 ... b are not empty.
# This is a 'change'.
# b) last1 ... a is empty, last2 ... b is not.
# This is an 'addition'.
# c) last1 ... a is not empty, last2 ... b is empty.
# This is a deletion.
# d) If both ranges are empty we can ignore the
# two current indices. For merging we simply
# take the information from the input.
set empty1 [expr {($a - $last1) <= 1}]
set empty2 [expr {($b - $last2) <= 1}]
if {$empty1 && $empty2} {
# Case (d), add 'unchanged' chunk.
set type --
foreach {type left right} [lindex $result end] break
if {[string match unchanged $type]} {
# There is an existing result to extend
lset left end $a
lset right end $b
lset result end [::list unchanged $left $right]
} else {
# There is an unchanged result at the start of the list;
# it may be extended.
lappend result [::list unchanged [::list $a $a] [::list $b $b]]
}
} else {
if {$empty1} {
# Case (b), 'addition'.
incr last2 ; incr b -1
lappend result [::list added [::list $last1 $a] [::list $last2 $b]]
incr b
} elseif {$empty2} {
# Case (c), 'deletion'
incr last1 ; incr a -1
lappend result [::list deleted [::list $last1 $a] [::list $last2 $b]]
incr a
} else {
# Case (a), 'change'.
incr last1 ; incr a -1
incr last2 ; incr b -1
lappend result [::list changed [::list $last1 $a] [::list $last2 $b]]
incr a
incr b
}
# Finally, the two matching lines are a new unchanged region
lappend result [::list unchanged [::list $a $a] [::list $b $b]]
}
set last1 $a
set last2 $b
}
# Handle the last chunk, using the information about the length of
# the original sequences.
set empty1 [expr {($len1 - $last1) <= 1}]
set empty2 [expr {($len2 - $last2) <= 1}]
if {$empty1 && $empty2} {
# Case (d), ignore the indices
} elseif {$empty1} {
# Case (b), 'addition'.
incr last2 ; incr len2 -1
lappend result [::list added [::list $last1 $len1] [::list $last2 $len2]]
} elseif {$empty2} {
# Case (c), 'deletion'
incr last1 ; incr len1 -1
lappend result [::list deleted [::list $last1 $len1] [::list $last2 $len2]]
} else {
# Case (q), 'change'.
incr last1 ; incr len1 -1
incr last2 ; incr len2 -1
lappend result [::list changed [::list $last1 $len1] [::list $last2 $len2]]
}
return $result
}
# ::struct::list::Lreverse --
#
# Reverses the contents of the list and returns the reversed
# list as the result of the command.
#
# Parameters:
# sequence List to be reversed.
#
# Results:
# The sequence in reverse.
#
# Side effects:
# None.
proc ::struct::list::Lreverse {sequence} {
set l [::llength $sequence]
# Shortcut for lists where reversing yields the list itself
if {$l < 2} {return $sequence}
# Perform true reversal
set res [::list]
while {$l} {
::lappend res [::lindex $sequence [incr l -1]]
}
return $res
}
# ::struct::list::Lassign --
#
# Assign list elements to variables.
#
# Parameters:
# sequence List to assign
# args Names of the variables to assign to.
#
# Results:
# The unassigned part of the sequence. Can be empty.
#
# Side effects:
# None.
# Do a compatibility version of [assign] for pre-8.5 versions of Tcl.
if { [package vcompare [package provide Tcl] 8.5] < 0 } {
# 8.4
proc ::struct::list::Lassign {sequence v args} {
set args [linsert $args 0 $v]
set a [::llength $args]
# Nothing to assign.
#if {$a == 0} {return $sequence}
# Perform assignments
set i 0
foreach v $args {
upvar 1 $v var
set var [::lindex $sequence $i]
incr i
}
# Return remainder, if there is any.
return [::lrange $sequence $a end]
}
} else {
# For 8.5+ simply redirect the method to the core command.
interp alias {} ::struct::list::Lassign {} lassign
}
# ::struct::list::Lshift --
#
# Shift a list in a variable one element down, and return first element
#
# Parameters:
# listvar Name of variable containing the list to shift.
#
# Results:
# The first element of the list.
#
# Side effects:
# After the call the list variable will contain
# the second to last elements of the list.
proc ::struct::list::Lshift {listvar} {
upvar 1 $listvar list
set list [Lassign [K $list [set list {}]] v]
return $v
}
# ::struct::list::Lflatten --
#
# Remove nesting from the input
#
# Parameters:
# sequence List to flatten
#
# Results:
# The input list with one or all levels of nesting removed.
#
# Side effects:
# None.
proc ::struct::list::Lflatten {args} {
if {[::llength $args] < 1} {
return -code error \
"wrong#args: should be \"::struct::list::Lflatten ?-full? ?--? sequence\""
}
set full 0
while {[string match -* [set opt [::lindex $args 0]]]} {
switch -glob -- $opt {
-full {set full 1}
-- {
set args [::lrange $args 1 end]
break ; # fix ticket 6e778502b8 -- break exits while loop
}
default {
return -code error "Unknown option \"$opt\", should be either -full, or --"
}
}
set args [::lrange $args 1 end]
}
if {[::llength $args] != 1} {
return -code error \
"wrong#args: should be \"::struct::list::Lflatten ?-full? ?--? sequence\""
}
set sequence [::lindex $args 0]
set cont 1
while {$cont} {
set cont 0
set result [::list]
foreach item $sequence {
# catch/llength detects if the item is following the list
# syntax.
if {[catch {llength $item} len]} {
# Element is not a list in itself, no flatten, add it
# as is.
lappend result $item
} else {
# Element is parseable as list, add all sub-elements
# to the result.
foreach e $item {
lappend result $e
}
}
}
if {$full && [string compare $sequence $result]} {set cont 1}
set sequence $result
}
return $result
}
# ::struct::list::Lmap --
#
# Apply command to each element of a list and return concatenated results.
#
# Parameters:
# sequence List to operate on
# cmdprefix Operation to perform on the elements.
#
# Results:
# List containing the result of applying cmdprefix to the elements of the
# sequence.
#
# Side effects:
# None of its own, but the command prefix can perform arbitry actions.
proc ::struct::list::Lmap {sequence cmdprefix} {
# Shortcut when nothing is to be done.
if {[::llength $sequence] == 0} {return $sequence}
set res [::list]
foreach item $sequence {
lappend res [uplevel 1 [linsert $cmdprefix end $item]]
}
return $res
}
# ::struct::list::Lmapfor --
#
# Apply a script to each element of a list and return concatenated results.
#
# Parameters:
# sequence List to operate on
# script The script to run on the elements.
#
# Results:
# List containing the result of running script on the elements of the
# sequence.
#
# Side effects:
# None of its own, but the script can perform arbitry actions.
proc ::struct::list::Lmapfor {var sequence script} {
# Shortcut when nothing is to be done.
if {[::llength $sequence] == 0} {return $sequence}
upvar 1 $var item
set res [::list]
foreach item $sequence {
lappend res [uplevel 1 $script]
}
return $res
}
# ::struct::list::Lfilter --
#
# Apply command to each element of a list and return elements passing the test.
#
# Parameters:
# sequence List to operate on
# cmdprefix Test to perform on the elements.
#
# Results:
# List containing the elements of the input passing the test command.
#
# Side effects:
# None of its own, but the command prefix can perform arbitrary actions.
proc ::struct::list::Lfilter {sequence cmdprefix} {
# Shortcut when nothing is to be done.
if {[::llength $sequence] == 0} {return $sequence}
return [uplevel 1 [::list ::struct::list::Lfold $sequence {} [::list ::struct::list::FTest $cmdprefix]]]
}
proc ::struct::list::FTest {cmdprefix result item} {
set pass [uplevel 1 [::linsert $cmdprefix end $item]]
if {$pass} {::lappend result $item}
return $result
}
# ::struct::list::Lfilterfor --
#
# Apply expr condition to each element of a list and return elements passing the test.
#
# Parameters:
# sequence List to operate on
# expr Test to perform on the elements.
#
# Results:
# List containing the elements of the input passing the test expression.
#
# Side effects:
# None of its own, but the command prefix can perform arbitrary actions.
proc ::struct::list::Lfilterfor {var sequence expr} {
# Shortcut when nothing is to be done.
if {[::llength $sequence] == 0} {return $sequence}
upvar 1 $var item
set result {}
foreach item $sequence {
if {[uplevel 1 [::list ::expr $expr]]} {
lappend result $item
}
}
return $result
}
# ::struct::list::Lsplit --
#
# Apply command to each element of a list and return elements passing
# and failing the test. Basic idea by Salvatore Sanfilippo
# (http://wiki.tcl.tk/lsplit). The implementation here is mine (AK),
# and the interface is slightly different (Command prefix with the
# list element given to it as argument vs. variable + script).
#
# Parameters:
# sequence List to operate on
# cmdprefix Test to perform on the elements.
# args = empty | (varPass varFail)
#
# Results:
# If the variables are specified then a list containing the
# numbers of passing and failing elements, in this
# order. Otherwise a list having two elements, the lists of
# passing and failing elements, in this order.
#
# Side effects:
# None of its own, but the command prefix can perform arbitrary actions.
proc ::struct::list::Lsplit {sequence cmdprefix args} {
set largs [::llength $args]
if {$largs == 0} {
# Shortcut when nothing is to be done.
if {[::llength $sequence] == 0} {return {{} {}}}
return [Lfold $sequence {} [::list ::struct::list::PFTest $cmdprefix]]
} elseif {$largs == 2} {
# Shortcut when nothing is to be done.
foreach {pv fv} $args break
upvar 1 $pv pass $fv fail
if {[::llength $sequence] == 0} {
set pass {}
set fail {}
return {0 0}
}
foreach {pass fail} [uplevel 1 [::list ::struct::list::Lfold $sequence {} [::list ::struct::list::PFTest $cmdprefix]]] break
return [::list [llength $pass] [llength $fail]]
} else {
return -code error \
"wrong#args: should be \"::struct::list::Lsplit sequence cmdprefix ?passVar failVar?"
}
}
proc ::struct::list::PFTest {cmdprefix result item} {
set passing [uplevel 1 [::linsert $cmdprefix end $item]]
set pass {} ; set fail {}
foreach {pass fail} $result break
if {$passing} {
::lappend pass $item
} else {
::lappend fail $item
}
return [::list $pass $fail]
}
# ::struct::list::Lfold --
#
# Fold list into one value.
#
# Parameters:
# sequence List to operate on
# cmdprefix Operation to perform on the elements.
#
# Results:
# Result of applying cmdprefix to the elements of the
# sequence.
#
# Side effects:
# None of its own, but the command prefix can perform arbitry actions.
proc ::struct::list::Lfold {sequence initialvalue cmdprefix} {
# Shortcut when nothing is to be done.
if {[::llength $sequence] == 0} {return $initialvalue}
set res $initialvalue
foreach item $sequence {
set res [uplevel 1 [linsert $cmdprefix end $res $item]]
}
return $res
}
# ::struct::list::Liota --
#
# Return a list containing the integer numbers 0 ... n-1
#
# Parameters:
# n First number not in the generated list.
#
# Results:
# A list containing integer numbers.
#
# Side effects:
# None
proc ::struct::list::Liota {n} {
set retval [::list]
for {set i 0} {$i < $n} {incr i} {
::lappend retval $i
}
return $retval
}
# ::struct::list::Ldelete --
#
# Delete an element from a list by name.
# Similar to 'struct::set exclude', however
# this here preserves order and list intrep.
#
# Parameters:
# a First list to compare.
# b Second list to compare.
#
# Results:
# A boolean. True if the lists are delete.
#
# Side effects:
# None
proc ::struct::list::Ldelete {var item} {
upvar 1 $var list
set pos [lsearch -exact $list $item]
if {$pos < 0} return
set list [lreplace [K $list [set list {}]] $pos $pos]
return
}
# ::struct::list::Lequal --
#
# Compares two lists for equality
# (Same length, Same elements in same order).
#
# Parameters:
# a First list to compare.
# b Second list to compare.
#
# Results:
# A boolean. True if the lists are equal.
#
# Side effects:
# None
proc ::struct::list::Lequal {a b} {
# Author of this command is "Richard Suchenwirth"
if {[::llength $a] != [::llength $b]} {return 0}
if {[::lindex $a 0] == $a && [::lindex $b 0] == $b} {return [string equal $a $b]}
foreach i $a j $b {if {![Lequal $i $j]} {return 0}}
return 1
}
# ::struct::list::Lrepeatn --
#
# Create a list repeating the same value over again.
#
# Parameters:
# value value to use in the created list.
# args Dimension(s) of the (nested) list to create.
#
# Results:
# A list
#
# Side effects:
# None
proc ::struct::list::Lrepeatn {value args} {
if {[::llength $args] == 1} {set args [::lindex $args 0]}
set buf {}
foreach number $args {
incr number 0 ;# force integer (1)
set buf {}
for {set i 0} {$i<$number} {incr i} {
::lappend buf $value
}
set value $buf
}
return $buf
# (1): See 'Stress testing' (wiki) for why this makes the code safer.
}
# ::struct::list::Lrepeat --
#
# Create a list repeating the same value over again.
# [Identical to the Tcl 8.5 lrepeat command]
#
# Parameters:
# n Number of replications.
# args values to use in the created list.
#
# Results:
# A list
#
# Side effects:
# None
# Do a compatibility version of [repeat] for pre-8.5 versions of Tcl.
if { [package vcompare [package provide Tcl] 8.5] < 0 } {
proc ::struct::list::Lrepeat {positiveCount value args} {
if {![string is integer -strict $positiveCount]} {
return -code error "expected integer but got \"$positiveCount\""
} elseif {$positiveCount < 1} {
return -code error {must have a count of at least 1}
}
set args [linsert $args 0 $value]
if {$positiveCount == 1} {
# Tcl itself has already listified the incoming parameters
# via 'args'.
return $args
}
set result [::list]
while {$positiveCount > 0} {
if {($positiveCount % 2) == 0} {
set args [concat $args $args]
set positiveCount [expr {$positiveCount/2}]
} else {
set result [concat $result $args]
incr positiveCount -1
}
}
return $result
}
} else {
# For 8.5 simply redirect the method to the core command.
interp alias {} ::struct::list::Lrepeat {} lrepeat
}
# ::struct::list::LdbJoin(Keyed) --
#
# Relational table joins.
#
# Parameters:
# args key specs and tables to join
#
# Results:
# A table/matrix as nested list. See
# struct/matrix set/get rect for structure.
#
# Side effects:
# None
proc ::struct::list::LdbJoin {args} {
# --------------------------------
# Process options ...
set mode inner
set keyvar {}
while {[llength $args]} {
set err [::cmdline::getopt args {inner left right full keys.arg} opt arg]
if {$err == 1} {
if {[string equal $opt keys]} {
set keyvar $arg
} else {
set mode $opt
}
} elseif {$err < 0} {
return -code error "wrong#args: dbJoin ?-inner|-left|-right|-full? ?-keys varname? \{key table\}..."
} else {
# Non-option argument found, stop processing.
break
}
}
set inner [string equal $mode inner]
set innerorleft [expr {$inner || [string equal $mode left]}]
# --------------------------------
# Process tables ...
if {([llength $args] % 2) != 0} {
return -code error "wrong#args: dbJoin ?-inner|-left|-right|-full? \{key table\}..."
}
# One table only, join is identity
if {[llength $args] == 2} {return [lindex $args 1]}
# Use first table for setup.
foreach {key table} $args break
# Check for possible early abort
if {$innerorleft && ([llength $table] == 0)} {return {}}
set width 0
array set state {}
set keylist [InitMap state width $key $table]
# Extend state with the remaining tables.
foreach {key table} [lrange $args 2 end] {
# Check for possible early abort
if {$inner && ([llength $table] == 0)} {return {}}
switch -exact -- $mode {
inner {set keylist [MapExtendInner state $key $table]}
left {set keylist [MapExtendLeftOuter state width $key $table]}
right {set keylist [MapExtendRightOuter state width $key $table]}
full {set keylist [MapExtendFullOuter state width $key $table]}
}
# Check for possible early abort
if {$inner && ([llength $keylist] == 0)} {return {}}
}
if {[string length $keyvar]} {
upvar 1 $keyvar keys
set keys $keylist
}
return [MapToTable state $keylist]
}
proc ::struct::list::LdbJoinKeyed {args} {
# --------------------------------
# Process options ...
set mode inner
set keyvar {}
while {[llength $args]} {
set err [::cmdline::getopt args {inner left right full keys.arg} opt arg]
if {$err == 1} {
if {[string equal $opt keys]} {
set keyvar $arg
} else {
set mode $opt
}
} elseif {$err < 0} {
return -code error "wrong#args: dbJoin ?-inner|-left|-right|-full? table..."
} else {
# Non-option argument found, stop processing.
break
}
}
set inner [string equal $mode inner]
set innerorleft [expr {$inner || [string equal $mode left]}]
# --------------------------------
# Process tables ...
# One table only, join is identity
if {[llength $args] == 1} {
return [Dekey [lindex $args 0]]
}
# Use first table for setup.
set table [lindex $args 0]
# Check for possible early abort
if {$innerorleft && ([llength $table] == 0)} {return {}}
set width 0
array set state {}
set keylist [InitKeyedMap state width $table]
# Extend state with the remaining tables.
foreach table [lrange $args 1 end] {
# Check for possible early abort
if {$inner && ([llength $table] == 0)} {return {}}
switch -exact -- $mode {
inner {set keylist [MapKeyedExtendInner state $table]}
left {set keylist [MapKeyedExtendLeftOuter state width $table]}
right {set keylist [MapKeyedExtendRightOuter state width $table]}
full {set keylist [MapKeyedExtendFullOuter state width $table]}
}
# Check for possible early abort
if {$inner && ([llength $keylist] == 0)} {return {}}
}
if {[string length $keyvar]} {
upvar 1 $keyvar keys
set keys $keylist
}
return [MapToTable state $keylist]
}
## Helpers for the relational joins.
## Map is an array mapping from keys to a list
## of rows with that key
proc ::struct::list::Cartesian {leftmap rightmap key} {
upvar $leftmap left $rightmap right
set joined [::list]
foreach lrow $left($key) {
foreach row $right($key) {
lappend joined [concat $lrow $row]
}
}
set left($key) $joined
return
}
proc ::struct::list::SingleRightCartesian {mapvar key rightrow} {
upvar $mapvar map
set joined [::list]
foreach lrow $map($key) {
lappend joined [concat $lrow $rightrow]
}
set map($key) $joined
return
}
proc ::struct::list::MapToTable {mapvar keys} {
# Note: keys must not appear multiple times in the list.
upvar $mapvar map
set table [::list]
foreach k $keys {
foreach row $map($k) {lappend table $row}
}
return $table
}
## More helpers, core join operations: Init, Extend.
proc ::struct::list::InitMap {mapvar wvar key table} {
upvar $mapvar map $wvar width
set width [llength [lindex $table 0]]
foreach row $table {
set keyval [lindex $row $key]
if {[info exists map($keyval)]} {
lappend map($keyval) $row
} else {
set map($keyval) [::list $row]
}
}
return [array names map]
}
proc ::struct::list::MapExtendInner {mapvar key table} {
upvar $mapvar map
array set used {}
# Phase I - Find all keys in the second table matching keys in the
# first. Remember all their rows.
foreach row $table {
set keyval [lindex $row $key]
if {[info exists map($keyval)]} {
if {[info exists used($keyval)]} {
lappend used($keyval) $row
} else {
set used($keyval) [::list $row]
}
} ; # else: Nothing to do for missing keys.
}
# Phase II - Merge the collected rows of the second (right) table
# into the map, and eliminate all entries which have no keys in
# the second table.
foreach k [array names map] {
if {[info exists used($k)]} {
Cartesian map used $k
} else {
unset map($k)
}
}
return [array names map]
}
proc ::struct::list::MapExtendRightOuter {mapvar wvar key table} {
upvar $mapvar map $wvar width
array set used {}
# Phase I - We keep all keys of the right table, even if they are
# missing in the left one <=> Definition of right outer join.
set w [llength [lindex $table 0]]
foreach row $table {
set keyval [lindex $row $key]
if {[info exists used($keyval)]} {
lappend used($keyval) $row
} else {
set used($keyval) [::list $row]
}
}
# Phase II - Merge the collected rows of the second (right) table
# into the map, and eliminate all entries which have no keys in
# the second table. If there is nothing in the left table we
# create an appropriate empty row for the cartesian => definition
# of right outer join.
# We go through used, because map can be empty for outer
foreach k [array names map] {
if {![info exists used($k)]} {
unset map($k)
}
}
foreach k [array names used] {
if {![info exists map($k)]} {
set map($k) [::list [Lrepeatn {} $width]]
}
Cartesian map used $k
}
incr width $w
return [array names map]
}
proc ::struct::list::MapExtendLeftOuter {mapvar wvar key table} {
upvar $mapvar map $wvar width
array set used {}
## Keys: All in inner join + additional left keys
## == All left keys = array names map after
## all is said and done with it.
# Phase I - Find all keys in the second table matching keys in the
# first. Remember all their rows.
set w [llength [lindex $table 0]]
foreach row $table {
set keyval [lindex $row $key]
if {[info exists map($keyval)]} {
if {[info exists used($keyval)]} {
lappend used($keyval) $row
} else {
set used($keyval) [::list $row]
}
} ; # else: Nothing to do for missing keys.
}
# Phase II - Merge the collected rows of the second (right) table
# into the map. We keep entries which have no keys in the second
# table, we actually extend them <=> Left outer join.
foreach k [array names map] {
if {[info exists used($k)]} {
Cartesian map used $k
} else {
SingleRightCartesian map $k [Lrepeatn {} $w]
}
}
incr width $w
return [array names map]
}
proc ::struct::list::MapExtendFullOuter {mapvar wvar key table} {
upvar $mapvar map $wvar width
array set used {}
# Phase I - We keep all keys of the right table, even if they are
# missing in the left one <=> Definition of right outer join.
set w [llength [lindex $table 0]]
foreach row $table {
set keyval [lindex $row $key]
if {[info exists used($keyval)]} {
lappend used($keyval) $row
} else {
lappend keylist $keyval
set used($keyval) [::list $row]
}
}
# Phase II - Merge the collected rows of the second (right) table
# into the map. We keep entries which have no keys in the second
# table, we actually extend them <=> Left outer join.
# If there is nothing in the left table we create an appropriate
# empty row for the cartesian => definition of right outer join.
# We go through used, because map can be empty for outer
foreach k [array names map] {
if {![info exists used($k)]} {
SingleRightCartesian map $k [Lrepeatn {} $w]
}
}
foreach k [array names used] {
if {![info exists map($k)]} {
set map($k) [::list [Lrepeatn {} $width]]
}
Cartesian map used $k
}
incr width $w
return [array names map]
}
## Keyed helpers
proc ::struct::list::InitKeyedMap {mapvar wvar table} {
upvar $mapvar map $wvar width
set width [llength [lindex [lindex $table 0] 1]]
foreach row $table {
foreach {keyval rowdata} $row break
if {[info exists map($keyval)]} {
lappend map($keyval) $rowdata
} else {
set map($keyval) [::list $rowdata]
}
}
return [array names map]
}
proc ::struct::list::MapKeyedExtendInner {mapvar table} {
upvar $mapvar map
array set used {}
# Phase I - Find all keys in the second table matching keys in the
# first. Remember all their rows.
foreach row $table {
foreach {keyval rowdata} $row break
if {[info exists map($keyval)]} {
if {[info exists used($keyval)]} {
lappend used($keyval) $rowdata
} else {
set used($keyval) [::list $rowdata]
}
} ; # else: Nothing to do for missing keys.
}
# Phase II - Merge the collected rows of the second (right) table
# into the map, and eliminate all entries which have no keys in
# the second table.
foreach k [array names map] {
if {[info exists used($k)]} {
Cartesian map used $k
} else {
unset map($k)
}
}
return [array names map]
}
proc ::struct::list::MapKeyedExtendRightOuter {mapvar wvar table} {
upvar $mapvar map $wvar width
array set used {}
# Phase I - We keep all keys of the right table, even if they are
# missing in the left one <=> Definition of right outer join.
set w [llength [lindex $table 0]]
foreach row $table {
foreach {keyval rowdata} $row break
if {[info exists used($keyval)]} {
lappend used($keyval) $rowdata
} else {
set used($keyval) [::list $rowdata]
}
}
# Phase II - Merge the collected rows of the second (right) table
# into the map, and eliminate all entries which have no keys in
# the second table. If there is nothing in the left table we
# create an appropriate empty row for the cartesian => definition
# of right outer join.
# We go through used, because map can be empty for outer
foreach k [array names map] {
if {![info exists used($k)]} {
unset map($k)
}
}
foreach k [array names used] {
if {![info exists map($k)]} {
set map($k) [::list [Lrepeatn {} $width]]
}
Cartesian map used $k
}
incr width $w
return [array names map]
}
proc ::struct::list::MapKeyedExtendLeftOuter {mapvar wvar table} {
upvar $mapvar map $wvar width
array set used {}
## Keys: All in inner join + additional left keys
## == All left keys = array names map after
## all is said and done with it.
# Phase I - Find all keys in the second table matching keys in the
# first. Remember all their rows.
set w [llength [lindex $table 0]]
foreach row $table {
foreach {keyval rowdata} $row break
if {[info exists map($keyval)]} {
if {[info exists used($keyval)]} {
lappend used($keyval) $rowdata
} else {
set used($keyval) [::list $rowdata]
}
} ; # else: Nothing to do for missing keys.
}
# Phase II - Merge the collected rows of the second (right) table
# into the map. We keep entries which have no keys in the second
# table, we actually extend them <=> Left outer join.
foreach k [array names map] {
if {[info exists used($k)]} {
Cartesian map used $k
} else {
SingleRightCartesian map $k [Lrepeatn {} $w]
}
}
incr width $w
return [array names map]
}
proc ::struct::list::MapKeyedExtendFullOuter {mapvar wvar table} {
upvar $mapvar map $wvar width
array set used {}
# Phase I - We keep all keys of the right table, even if they are
# missing in the left one <=> Definition of right outer join.
set w [llength [lindex $table 0]]
foreach row $table {
foreach {keyval rowdata} $row break
if {[info exists used($keyval)]} {
lappend used($keyval) $rowdata
} else {
lappend keylist $keyval
set used($keyval) [::list $rowdata]
}
}
# Phase II - Merge the collected rows of the second (right) table
# into the map. We keep entries which have no keys in the second
# table, we actually extend them <=> Left outer join.
# If there is nothing in the left table we create an appropriate
# empty row for the cartesian => definition of right outer join.
# We go through used, because map can be empty for outer
foreach k [array names map] {
if {![info exists used($k)]} {
SingleRightCartesian map $k [Lrepeatn {} $w]
}
}
foreach k [array names used] {
if {![info exists map($k)]} {
set map($k) [::list [Lrepeatn {} $width]]
}
Cartesian map used $k
}
incr width $w
return [array names map]
}
proc ::struct::list::Dekey {keyedtable} {
set table [::list]
foreach row $keyedtable {lappend table [lindex $row 1]}
return $table
}
# ::struct::list::Lswap --
#
# Exchange two elements of a list.
#
# Parameters:
# listvar Name of the variable containing the list to manipulate.
# i, j Indices of the list elements to exchange.
#
# Results:
# The modified list
#
# Side effects:
# None
proc ::struct::list::Lswap {listvar i j} {
upvar $listvar list
if {($i < 0) || ($j < 0)} {
return -code error {list index out of range}
}
set len [llength $list]
if {($i >= $len) || ($j >= $len)} {
return -code error {list index out of range}
}
if {$i != $j} {
set tmp [lindex $list $i]
lset list $i [lindex $list $j]
lset list $j $tmp
}
return $list
}
# ::struct::list::Lfirstperm --
#
# Returns the lexicographically first permutation of the
# specified list.
#
# Parameters:
# list The list whose first permutation is sought.
#
# Results:
# A modified list containing the lexicographically first
# permutation of the input.
#
# Side effects:
# None
proc ::struct::list::Lfirstperm {list} {
return [lsort $list]
}
# ::struct::list::Lnextperm --
#
# Accepts a permutation of a set of elements and returns the
# next permutatation in lexicographic sequence.
#
# Parameters:
# list The list containing the current permutation.
#
# Results:
# A modified list containing the lexicographically next
# permutation after the input permutation.
#
# Side effects:
# None
proc ::struct::list::Lnextperm {perm} {
# Find the smallest subscript j such that we have already visited
# all permutations beginning with the first j elements.
set len [expr {[llength $perm] - 1}]
set j $len
set ajp1 [lindex $perm $j]
while { $j > 0 } {
incr j -1
set aj [lindex $perm $j]
if { [string compare $ajp1 $aj] > 0 } {
set foundj {}
break
}
set ajp1 $aj
}
if { ![info exists foundj] } return
# Find the smallest element greater than the j'th among the elements
# following aj. Let its index be l, and interchange aj and al.
set l $len
while { [string compare $aj [set al [lindex $perm $l]]] >= 0 } {
incr l -1
}
lset perm $j $al
lset perm $l $aj
# Reverse a_j+1 ... an
set k [expr {$j + 1}]
set l $len
while { $k < $l } {
set al [lindex $perm $l]
lset perm $l [lindex $perm $k]
lset perm $k $al
incr k
incr l -1
}
return $perm
}
# ::struct::list::Lpermutations --
#
# Returns a list containing all the permutations of the
# specified list, in lexicographic order.
#
# Parameters:
# list The list whose permutations are sought.
#
# Results:
# A list of lists, containing all permutations of the
# input.
#
# Side effects:
# None
proc ::struct::list::Lpermutations {list} {
if {[llength $list] < 2} {
return [::list $list]
}
set res {}
set p [Lfirstperm $list]
while {[llength $p]} {
lappend res $p
set p [Lnextperm $p]
}
return $res
}
# ::struct::list::Lforeachperm --
#
# Executes a script for all the permutations of the
# specified list, in lexicographic order.
#
# Parameters:
# var Name of the loop variable.
# list The list whose permutations are sought.
# body The tcl script to run per permutation of
# the input.
#
# Results:
# The empty string.
#
# Side effects:
# None
proc ::struct::list::Lforeachperm {var list body} {
upvar $var loopvar
if {[llength $list] < 2} {
set loopvar $list
# TODO run body.
# The first invocation of the body, also the last, as only one
# permutation is possible. That makes handling of the result
# codes easier.
set code [catch {uplevel 1 $body} result]
# decide what to do upon the return code:
#
# 0 - the body executed successfully
# 1 - the body raised an error
# 2 - the body invoked [return]
# 3 - the body invoked [break]
# 4 - the body invoked [continue]
# everything else - return and pass on the results
#
switch -exact -- $code {
0 {}
1 {
return -errorinfo [ErrorInfoAsCaller uplevel foreachperm] \
-errorcode $::errorCode -code error $result
}
3 {}
4 {}
default {
# Includes code 2
return -code $code $result
}
}
return
}
set p [Lfirstperm $list]
while {[llength $p]} {
set loopvar $p
set code [catch {uplevel 1 $body} result]
# decide what to do upon the return code:
#
# 0 - the body executed successfully
# 1 - the body raised an error
# 2 - the body invoked [return]
# 3 - the body invoked [break]
# 4 - the body invoked [continue]
# everything else - return and pass on the results
#
switch -exact -- $code {
0 {}
1 {
return -errorinfo [ErrorInfoAsCaller uplevel foreachperm] \
-errorcode $::errorCode -code error $result
}
3 {
# FRINK: nocheck
return
}
4 {}
default {
return -code $code $result
}
}
set p [Lnextperm $p]
}
return
}
proc ::struct::list::Lshuffle {list} {
for {set i [llength $list]} {$i > 1} {lset list $j $t} {
set j [expr {int(rand() * $i)}]
set t [lindex $list [incr i -1]]
lset list $i [lindex $list $j]
}
return $list
}
# ### ### ### ######### ######### #########
proc ::struct::list::ErrorInfoAsCaller {find replace} {
set info $::errorInfo
set i [string last "\n (\"$find" $info]
if {$i == -1} {return $info}
set result [string range $info 0 [incr i 6]] ;# keep "\n (\""
append result $replace ;# $find -> $replace
incr i [string length $find]
set j [string first ) $info [incr i]] ;# keep rest of parenthetical
append result [string range $info $i $j]
return $result
}
# ### ### ### ######### ######### #########
## Ready
namespace eval ::struct {
# Get 'list::list' into the general structure namespace.
namespace import -force list::list
namespace export list
}
package provide struct::list 1.8.4
|