Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

r""" 

Elements, Array and Lists With Clone Protocol 

  

This module defines several classes which are subclasses of 

:class:`Element<sage.structure.element.Element>` and which roughly implement 

the "prototype" design pattern (see [Prototype_pattern]_, [GHJV1994]_). Those classes are 

intended to be used to model *mathematical* objects, which are by essence 

immutable. However, in many occasions, one wants to construct the 

data-structure encoding of a new mathematical object by small modifications of 

the data structure encoding some already built object. For the resulting 

data-structure to correctly encode the mathematical object, some structural 

invariants must hold. One problem is that, in many cases, during the 

modification process, there is no possibility but to break the invariants. 

  

For example, in a list modeling a permutation of `\{1,\dots,n\}`, the integers 

must be distinct. A very common operation is to take a permutation to make a 

copy with some small modifications, like exchanging two consecutive values in 

the list or cycling some values. Though the result is clearly a permutations 

there's no way to avoid breaking the permutations invariants at some point 

during the modifications. 

  

The main purpose of this module is to define the class 

  

- :class:`ClonableElement` as an abstract super class, 

  

and its subclasses: 

  

- :class:`ClonableArray` for arrays (lists of fixed length) of objects; 

- :class:`ClonableList` for (resizable) lists of objects; 

- :class:`NormalizedClonableList` for lists of objects with a normalization method; 

- :class:`ClonableIntArray` for arrays of int. 

  

.. SEEALSO:: The following parents from :mod:`sage.structure.list_clone_demo` 

demonstrate how to use them: 

  

- ``IncreasingArrays()`` (see 

:class:`~sage.structure.list_clone_demo.IncreasingArray` 

and the parent class 

:class:`~sage.structure.list_clone_demo.IncreasingArrays`) 

- ``IncreasingLists()`` (see 

:class:`~sage.structure.list_clone_demo.IncreasingList` 

and the parent class 

:class:`~sage.structure.list_clone_demo.IncreasingLists`) 

- ``SortedLists()`` (see 

:class:`~sage.structure.list_clone_demo.SortedList` 

and the parent class 

:class:`~sage.structure.list_clone_demo.SortedLists`) 

- ``IncreasingIntArrays()`` (see 

:class:`~sage.structure.list_clone_demo.IncreasingIntArray` 

and the parent class 

:class:`~sage.structure.list_clone_demo.IncreasingIntArrays`) 

  

EXAMPLES: 

  

We now demonstrate how 

:class:`~sage.structure.list_clone_demo.IncreasingArray` works, creating an 

instance ``el`` through its parent ``IncreasingArrays()``:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: P = IncreasingArrays() 

sage: P([1, 4 ,8]) 

[1, 4, 8] 

  

If one tries to create this way a list which in not increasing, an error is 

raised:: 

  

sage: IncreasingArrays()([5, 4 ,8]) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

  

Once created modifying ``el`` is forbidden:: 

  

sage: el = P([1, 4 ,8]) 

sage: el[1] = 3 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

  

However, you can modify a temporarily mutable clone:: 

  

sage: with el.clone() as elc: 

....: elc[1] = 3 

sage: [el, elc] 

[[1, 4, 8], [1, 3, 8]] 

  

We check that the original and the modified copy now are in a proper immutable 

state:: 

  

sage: el.is_immutable(), elc.is_immutable() 

(True, True) 

sage: elc[1] = 5 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

  

You can break the property that the list is increasing during the 

modification:: 

  

sage: with el.clone() as elc2: 

....: elc2[1] = 12 

....: print(elc2) 

....: elc2[2] = 25 

[1, 12, 8] 

sage: elc2 

[1, 12, 25] 

  

But this property must be restored at the end of the ``with`` block; otherwise 

an error is raised:: 

  

sage: with elc2.clone() as el3: 

....: el3[1] = 100 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

  

Finally, as an alternative to the ``with`` syntax one can use:: 

  

sage: el4 = copy(elc2) 

sage: el4[1] = 10 

sage: el4.set_immutable() 

sage: el4.check() 

  

REFERENCES: 

  

- [Prototype_pattern]_ 

- [GHJV1994]_ 

  

AUTHORS: 

  

- Florent Hivert (2010-03): initial revision 

""" 

  

#***************************************************************************** 

# Copyright (C) 2009-2010 Florent Hivert <Florent.Hivert@univ-rouen.fr> 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

  

from __future__ import absolute_import, print_function 

  

from cpython.list cimport * 

from cpython.int cimport * 

from cpython.ref cimport * 

  

from cysignals.memory cimport check_reallocarray, sig_free 

  

import sage 

from sage.ext.stdsage cimport HAS_DICTIONARY 

from sage.structure.element cimport Element 

from sage.structure.parent cimport Parent 

from sage.structure.richcmp cimport richcmp 

  

############################################################################ 

### Basic clone elements ### 

############################################################################ 

cdef class ClonableElement(Element): 

r""" 

Abstract class for elements with clone protocol 

  

This class is a subclass of :class:`Element<sage.structure.element.Element>` 

and implements the "prototype" design pattern (see [Prototype_pattern]_, [GHJV1994]_). The role 

of this class is: 

  

- to manage copy and mutability and hashing of elements 

- to ensure that at the end of a piece of code an object is restored in a 

meaningful mathematical state. 

  

A class ``C`` inheriting from :class:`ClonableElement` must implement 

the following two methods 

  

- ``obj.__copy__()`` -- returns a fresh copy of obj 

- ``obj.check()`` -- returns nothing, raise an exception if ``obj`` 

doesn't satisfy the data structure invariants 

  

and ensure to call ``obj._require_mutable()`` at the beginning of any 

modifying method. 

  

Additionally, one can also implement 

  

- ``obj._hash_()`` -- return the hash value of ``obj``. 

  

Then, given an instance ``obj`` of ``C``, the following sequences of 

instructions ensures that the invariants of ``new_obj`` are properly 

restored at the end:: 

  

with obj.clone() as new_obj: 

... 

# lot of invariant breaking modifications on new_obj 

... 

# invariants are ensured to be fulfilled 

  

The following equivalent sequence of instructions can be used if speed is 

needed, in particular in Cython code:: 

  

new_obj = obj.__copy__() 

... 

# lot of invariant breaking modifications on new_obj 

... 

new_obj.set_immutable() 

new_obj.check() 

# invariants are ensured to be fulfilled 

  

Finally, if the class implements the ``_hash_`` method, then 

:class:`ClonableElement` ensures that the hash value can only be 

computed on an immutable object. It furthermore caches it so that 

it is only computed once. 

  

.. warning:: for the hash caching mechanism to work correctly, the hash 

value cannot be 0. 

  

EXAMPLES: 

  

The following code shows a minimal example of usage of 

:class:`ClonableElement`. We implement a class or pairs `(x,y)` 

such that `x < y`:: 

  

sage: from sage.structure.list_clone import ClonableElement 

sage: class IntPair(ClonableElement): 

....: def __init__(self, parent, x, y): 

....: ClonableElement.__init__(self, parent=parent) 

....: self._x = x 

....: self._y = y 

....: self.set_immutable() 

....: self.check() 

....: def _repr_(self): 

....: return "(x=%s, y=%s)"%(self._x, self._y) 

....: def check(self): 

....: if self._x >= self._y: 

....: raise ValueError("Incorrectly ordered pair") 

....: def get_x(self): return self._x 

....: def get_y(self): return self._y 

....: def set_x(self, v): self._require_mutable(); self._x = v 

....: def set_y(self, v): self._require_mutable(); self._y = v 

  

.. NOTE:: we don't need to define ``__copy__`` since it is properly 

inherited from :class:`Element<sage.structure.element.Element>`. 

  

We now demonstrate the behavior. Let's create an ``IntPair``:: 

  

sage: myParent = Parent() 

sage: el = IntPair(myParent, 1, 3); el 

(x=1, y=3) 

sage: el.get_x() 

1 

  

Modifying it is forbidden:: 

  

sage: el.set_x(4) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

  

However, you can modify a mutable copy:: 

  

sage: with el.clone() as el1: 

....: el1.set_x(2) 

sage: [el, el1] 

[(x=1, y=3), (x=2, y=3)] 

  

We check that the original and the modified copy are in a proper immutable 

state:: 

  

sage: el.is_immutable(), el1.is_immutable() 

(True, True) 

sage: el1.set_x(4) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

  

A modification which doesn't restore the invariant `x < y` at the end is 

illegal and raise an exception:: 

  

sage: with el.clone() as elc2: 

....: elc2.set_x(5) 

Traceback (most recent call last): 

... 

ValueError: Incorrectly ordered pair 

""" 

def __cinit__(self): 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) # indirect doctest 

sage: el.is_immutable() 

True 

""" 

self._needs_check = True 

self._is_immutable = False 

self._hash = 0 

  

cpdef bint _require_mutable(self) except -2: 

""" 

Check that ``self`` is mutable. 

  

Raise a ``ValueError`` if ``self`` is immutable. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el._require_mutable() 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

""" 

if self._is_immutable: 

raise ValueError("object is immutable; please change a copy instead.") 

  

cpdef bint is_mutable(self): 

""" 

Returns ``True`` if ``self`` is mutable (can be changed) and ``False`` 

if it is not. 

  

To make this object immutable use ``self.set_immutable()``. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el.is_mutable() 

False 

sage: copy(el).is_mutable() 

True 

sage: with el.clone() as el1: 

....: print([el.is_mutable(), el1.is_mutable()]) 

[False, True] 

""" 

return not self._is_immutable 

  

cpdef bint is_immutable(self): 

""" 

Returns ``True`` if ``self`` is immutable (can not be changed) 

and ``False`` if it is not. 

  

To make ``self`` immutable use ``self.set_immutable()``. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el.is_immutable() 

True 

sage: copy(el).is_immutable() 

False 

sage: with el.clone() as el1: 

....: print([el.is_immutable(), el1.is_immutable()]) 

[True, False] 

""" 

return self._is_immutable 

  

cpdef set_immutable(self): 

""" 

Makes ``self`` immutable, so it can never again be changed. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el1 = copy(el); el1.is_mutable() 

True 

sage: el1.set_immutable(); el1.is_mutable() 

False 

sage: el1[2] = 4 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

""" 

self._is_immutable = True 

  

cpdef _set_mutable(self): 

""" 

Makes ``self`` mutable, so it can be changed. 

  

.. warning:: for internal use only. Casual users should make a copy 

using either the :meth:`__copy__` method or the :meth:`clone` 

protocol. Use only if you really know what you are doing. You 

should in particular make sure that you are the only owner of 

your object. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el._set_mutable(); el.is_mutable() 

True 

sage: hash(el) 

Traceback (most recent call last): 

... 

ValueError: cannot hash a mutable object. 

""" 

self._hash = 0 

self._is_immutable = False 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: hash(el) # random 

-309690657 

sage: el1 = copy(el); hash(el1) 

Traceback (most recent call last): 

... 

ValueError: cannot hash a mutable object. 

""" 

if self._hash == 0: 

if not self._is_immutable: 

raise ValueError("cannot hash a mutable object.") 

else: 

self._hash = self._hash_() 

return self._hash 

  

cpdef ClonableElement clone(self, bint check=True): 

""" 

Returns a clone that is mutable copy of ``self``. 

  

INPUT: 

  

- ``check`` -- a boolean indicating if ``self.check()`` must be called 

after modifications. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: with el.clone() as el1: 

....: el1[2] = 5 

sage: el1 

[1, 2, 5] 

""" 

cdef ClonableElement res 

res = self.__copy__() 

res._needs_check = check 

return res 

  

def __enter__(self): 

""" 

Implement the self guarding clone protocol. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el.clone().__enter__() 

[1, 2, 3] 

""" 

self._require_mutable() 

return self 

  

def __exit__(self, typ, value, tracback): 

""" 

Implement the self guarding clone protocol. 

  

.. NOTE:: The input argument are required by the ``with`` protocol but 

are ignored. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el1 = el.clone().__enter__() 

sage: el1.__exit__(None, None, None) 

False 

  

Lets try to make a broken list:: 

  

sage: elc2 = el.clone().__enter__() 

sage: elc2[1] = 7 

sage: elc2.__exit__(None, None, None) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

""" 

self.set_immutable() 

if __debug__ and self._needs_check: 

self.check() 

# is there a way if check() fails to replace self by a invalid object ? 

return False 

  

  

############################################################################ 

### The most common case of clone object : list with constraints ### 

############################################################################ 

cdef class ClonableArray(ClonableElement): 

""" 

Array with clone protocol 

  

The class of objects which are 

:class:`Element<sage.structure.element.Element>` behave as arrays 

(i.e. lists of fixed length) and implement the clone protocol. See 

:class:`ClonableElement` for details about clone protocol. 

  

INPUT: 

  

- ``parent`` -- a :class:`Parent<sage.structure.parent.Parent>` 

- ``lst`` -- a list 

- ``check`` -- a boolean specifying if the invariant must be checked 

using method :meth:`check`. 

- ``immutable`` -- a boolean telling wether the created element is 

immutable (defaults to ``True``) 

  

.. SEEALSO:: :class:`~sage.structure.list_clone_demo.IncreasingArray` for 

an example of usage. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: IA = IncreasingArrays() 

sage: ia1 = IA([1, 4, 6]); ia1 

[1, 4, 6] 

sage: with ia1.clone() as ia2: 

....: ia2[1] = 5 

sage: ia2 

[1, 5, 6] 

sage: with ia1.clone() as ia2: 

....: ia2[1] = 7 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

""" 

def __init__(self, Parent parent, lst, check = True, immutable = True): 

""" 

Initialize ``self`` 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: IncreasingArrays()([1,2,3]) 

[1, 2, 3] 

  

sage: el = IncreasingArrays()([3,2,1]) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

  

sage: IncreasingArrays()(None) 

Traceback (most recent call last): 

... 

TypeError: 'NoneType' object is not iterable 

  

You are not supposed to do the following (giving a wrong list and 

desactivating checks):: 

  

sage: broken = IncreasingArrays()([3,2,1], False) 

""" 

self._parent = parent 

self._list = list(lst) 

self._is_immutable = immutable 

if check: 

self.check() 

  

def _repr_(self): 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: IncreasingArrays()([1,2,3]) 

[1, 2, 3] 

""" 

return repr(self._list) 

  

def __nonzero__(self): 

""" 

Tests if self is not empty. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: IncreasingArrays()([1,2,3]).__nonzero__() 

True 

sage: IncreasingArrays()([]).__nonzero__() 

False 

""" 

return bool(self._list) 

  

cpdef list _get_list(self): 

""" 

Returns the list embedded in ``self``. 

  

.. warning:: No copy is performed. As a consequence, modifying the 

returned list is not allowed. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el._get_list() 

[1, 2, 3] 

""" 

return self._list 

  

cpdef _set_list(self, list lst): 

""" 

Set the list embedded in ``self``. 

  

.. warning:: No copy is performed. Modifying the list after calling 

``_set_list`` on it is not allowed. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el._set_list([1,4,5]) 

sage: el 

[1, 4, 5] 

""" 

self._list = lst 

  

def __len__(self): 

""" 

Returns the len of ``self`` 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: len(IncreasingArrays()([1,2,3])) 

3 

""" 

return len(self._list) 

  

def __getitem__(self, key): 

""" 

Returns the ``key``-th element of ``self`` 

  

It also works with slice returning a python list in this case. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: IncreasingArrays()([1,2,3])[1] 

2 

sage: IncreasingArrays()([1,2,3])[7] 

Traceback (most recent call last): 

... 

IndexError: list index out of range 

sage: IncreasingArrays()([1,2,3])[-1] 

3 

sage: IncreasingArrays()([1,2,3])[-1:] 

[3] 

sage: IncreasingArrays()([1,2,3])[:] 

[1, 2, 3] 

sage: type(IncreasingArrays()([1,2,3])[:]) 

<... 'list'> 

""" 

if isinstance(key, slice): 

self._list[key.start:key.stop:key.step] 

return self._list[key] 

  

def __setitem__(self, int key, value): 

""" 

Set the ``i``-th element of ``self`` 

  

An exception is raised if ``self`` is immutable. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4,10]) 

sage: elc = copy(el) 

sage: elc[1] = 3; elc 

[1, 3, 4, 10] 

sage: el[1] = 3 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: elc[5] = 3 

Traceback (most recent call last): 

... 

IndexError: list assignment index out of range 

""" 

self._require_mutable() 

self._list[key] = value 

  

cpdef object _getitem(self, int key): 

""" 

Same as :meth:`__getitem__` 

  

This is much faster when used with Cython and ``key`` is known to be 

an ``int``. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: IncreasingArrays()([1,2,3])._getitem(1) 

2 

sage: IncreasingArrays()([1,2,3])._getitem(5) 

Traceback (most recent call last): 

... 

IndexError: list index out of range 

""" 

return self._list[key] 

  

cpdef _setitem(self, int key, value): 

""" 

Same as :meth:`__setitem__` 

  

This is much faster when used with Cython and ``key`` is known to be 

an ``int``. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: elc._setitem(1, 3); elc 

[1, 3, 4] 

sage: el._setitem(1, 3) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: elc._setitem(5, 5) 

Traceback (most recent call last): 

... 

IndexError: list assignment index out of range 

""" 

self._require_mutable() 

self._list[key] = value 

  

def __iter__(self): 

""" 

Returns an iterator for ``self``:: 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4]) 

sage: list(iter(el)) 

[1, 2, 4] 

  

As a consequence ``min``, ``max`` behave properly:: 

  

sage: el = IncreasingArrays()([1,4,8]) 

sage: min(el), max(el) 

(1, 8) 

  

TESTS:: 

  

sage: list(iter(IncreasingArrays()([]))) 

[] 

""" 

return iter(self._list) 

  

def __contains__(self, item): 

""" 

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: c = IncreasingArrays()([1,2,4]) 

sage: 1 in c 

True 

sage: 5 in c 

False 

""" 

return item in self._list 

  

cpdef int index(self, x, start=None, stop=None) except -1: 

""" 

Returns the smallest ``k`` such that ``s[k] == x`` and ``i <= k < j`` 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: c = IncreasingArrays()([1,2,4]) 

sage: c.index(1) 

0 

sage: c.index(4) 

2 

sage: c.index(5) 

Traceback (most recent call last): 

... 

ValueError: 5 is not in list 

""" 

if start is None: 

return self._list.index(x) 

elif stop is None: 

return self._list.index(x, start) 

else: 

return self._list.index(x, start, stop) 

  

cpdef int count(self, key) except -1: 

""" 

Returns number of ``i``'s for which ``s[i] == key`` 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: c = IncreasingArrays()([1,2,2,4]) 

sage: c.count(1) 

1 

sage: c.count(2) 

2 

sage: c.count(3) 

0 

""" 

return self._list.count(key) 

  

def __hash__(self): 

""" 

Returns the hash value of ``self``. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: hash(el) # random 

-309690657 

sage: el1 = copy(el); hash(el1) 

Traceback (most recent call last): 

... 

ValueError: cannot hash a mutable object. 

""" 

if self._hash == 0: 

if not self._is_immutable: 

raise ValueError("cannot hash a mutable object.") 

else: 

self._hash = self._hash_() 

return self._hash 

  

# See protocol in comment in sage/structure/element.pyx 

cpdef _richcmp_(left, right, int op): 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: elc == el # indirect doctest 

True 

  

:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el1 = IncreasingArrays()([1,2,4]) 

sage: el2 = IncreasingArrays()([1,2,3]) 

sage: el1 == el1, el2 == el2, el1 == el2 # indirect doctest 

(True, True, False) 

sage: el1 <= el2, el1 >= el2, el2 <= el1 # indirect doctest 

(False, True, True) 

""" 

cdef ClonableArray rgt = <ClonableArray>right 

return richcmp(left._list, rgt._list, op) 

  

cpdef ClonableArray __copy__(self): 

""" 

Returns a copy of ``self`` 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: el[:] == elc[:] 

True 

sage: el is elc 

False 

  

We check that empty lists are correctly copied:: 

  

sage: el = IncreasingArrays()([]) 

sage: elc = copy(el) 

sage: el is elc 

False 

sage: elc.__nonzero__() 

False 

sage: elc.is_mutable() 

True 

  

We check that element with a ``__dict__`` are correctly copied:: 

  

sage: IL = IncreasingArrays() 

sage: class myClass(IL.element_class): pass 

sage: el = myClass(IL, []) 

sage: el.toto = 2 

sage: elc = copy(el) 

sage: elc.toto 

2 

""" 

cdef ClonableArray res 

cdef type t = type(self) 

res = t.__new__(t) 

res._parent = self._parent 

res._list = self._list[:] 

if HAS_DICTIONARY(self): 

res.__dict__ = self.__dict__.copy() 

return res 

  

cpdef check(self): 

""" 

Check that ``self`` fulfill the invariants 

  

This is an abstract method. Subclasses are supposed to overload 

``check``. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone import ClonableArray 

sage: ClonableArray(Parent(), [1,2,3]) # indirect doctest 

Traceback (most recent call last): 

... 

NotImplementedError: this should never be called, please overload the check method 

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4]) # indirect doctest 

""" 

raise NotImplementedError("this should never be called, please overload the check method") 

  

cpdef long _hash_(self) except? -1: 

""" 

Return the hash value of ``self``. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,3]) 

sage: el._hash_() # random 

-309711137 

sage: type(el._hash_()) == int 

True 

""" 

cdef long hv 

hv = hash(tuple(self._list)) 

return hash(self._parent) + hv 

  

def __reduce__(self): 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: el = IncreasingArrays()([1,2,4]) 

sage: loads(dumps(el)) 

[1, 2, 4] 

sage: t = el.__reduce__(); t 

(<built-in function _make_array_clone>, 

(<type 'sage.structure.list_clone_demo.IncreasingArray'>, 

<sage.structure.list_clone_demo.IncreasingArrays_with_category object at ...>, 

[1, 2, 4], 

True, 

True, 

None)) 

sage: t[0](*t[1]) 

[1, 2, 4] 

""" 

# Warning: don't pickle the hash value as it can change upon unpickling. 

if HAS_DICTIONARY(self): 

dic = self.__dict__ 

else: 

dic = None 

return (sage.structure.list_clone._make_array_clone, 

(type(self), self._parent, self._list, 

self._needs_check, self._is_immutable, dic)) 

  

  

##### Needed for unpickling ##### 

def _make_array_clone(clas, parent, list, needs_check, is_immutable, dic): 

""" 

Helpler to unpickle :class:`list_clone` instances. 

  

TESTS:: 

  

sage: from sage.structure.list_clone import _make_array_clone 

sage: from sage.structure.list_clone_demo import IncreasingArrays 

sage: ILs = IncreasingArrays() 

sage: el = _make_array_clone(ILs.element_class, ILs, [1,2,3], True, True, None) 

sage: el 

[1, 2, 3] 

sage: el == ILs([1,2,3]) 

True 

  

We check that element with a ``__dict__`` are correctly pickled:: 

  

sage: IL = IncreasingArrays() 

sage: class myClass(IL.element_class): pass 

sage: import __main__ 

sage: __main__.myClass = myClass 

sage: el = myClass(IL, []) 

sage: el.toto = 2 

sage: elc = loads(dumps(el)) 

sage: elc.toto 

2 

""" 

cdef ClonableArray res 

res = <ClonableArray> clas.__new__(clas) 

res._parent = parent 

res._list = list 

res._needs_check = needs_check 

res._is_immutable = is_immutable 

if dic is not None: 

res.__dict__ = dic 

return res 

  

  

############################################################################ 

### Clonable (Resizable) Lists ### 

############################################################################ 

cdef class ClonableList(ClonableArray): 

""" 

List with clone protocol 

  

The class of objects which are 

:class:`Element<sage.structure.element.Element>` behave as lists and 

implement the clone protocol. See :class:`ClonableElement` for details 

about clone protocol. 

  

.. SEEALSO:: :class:`~sage.structure.list_clone_demo.IncreasingList` for 

an example of usage. 

""" 

cpdef append(self, el): 

""" 

Appends ``el`` to ``self`` 

  

INPUT: ``el`` -- any object 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1]) 

sage: el.append(3) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: with el.clone() as elc: 

....: elc.append(4) 

....: elc.append(6) 

sage: elc 

[1, 4, 6] 

sage: with el.clone() as elc: 

....: elc.append(4) 

....: elc.append(2) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

""" 

self._require_mutable() 

self._list.append(el) 

  

cpdef extend(self, it): 

""" 

Extends ``self`` by the content of the iterable ``it`` 

  

INPUT: ``it`` -- any iterable 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1, 4, 5, 8, 9]) 

sage: el.extend((10,11)) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

  

sage: with el.clone() as elc: 

....: elc.extend((10,11)) 

sage: elc 

[1, 4, 5, 8, 9, 10, 11] 

  

sage: el2 = IncreasingLists()([15, 16]) 

sage: with el.clone() as elc: 

....: elc.extend(el2) 

sage: elc 

[1, 4, 5, 8, 9, 15, 16] 

  

sage: with el.clone() as elc: 

....: elc.extend((6,7)) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

""" 

self._require_mutable() 

self._list.extend(it) 

  

cpdef insert(self, int index, el): 

""" 

Inserts ``el`` in ``self`` at position ``index`` 

  

INPUT: 

  

- ``el`` -- any object 

- ``index`` -- any int 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1, 4, 5, 8, 9]) 

sage: el.insert(3, 6) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: with el.clone() as elc: 

....: elc.insert(3, 6) 

sage: elc 

[1, 4, 5, 6, 8, 9] 

sage: with el.clone() as elc: 

....: elc.insert(2, 6) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

""" 

self._require_mutable() 

self._list.insert(index, el) 

  

cpdef pop(self, int index=-1): 

""" 

Remove ``self[index]`` from ``self`` and returns it 

  

INPUT: ``index`` - any int, default to -1 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1, 4, 5, 8, 9]) 

sage: el.pop() 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: with el.clone() as elc: 

....: print(elc.pop()) 

9 

sage: elc 

[1, 4, 5, 8] 

sage: with el.clone() as elc: 

....: print(elc.pop(2)) 

5 

sage: elc 

[1, 4, 8, 9] 

""" 

self._require_mutable() 

return self._list.pop(index) 

  

cpdef remove(self, el): 

""" 

Remove the first occurrence of ``el`` from ``self`` 

  

INPUT: ``el`` - any object 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1, 4, 5, 8, 9]) 

sage: el.remove(4) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: with el.clone() as elc: 

....: elc.remove(4) 

sage: elc 

[1, 5, 8, 9] 

sage: with el.clone() as elc: 

....: elc.remove(10) 

Traceback (most recent call last): 

... 

ValueError: list.remove(x): x not in list 

""" 

self._require_mutable() 

return self._list.remove(el) 

  

def __setitem__(self, key, value): 

""" 

Set the ith element of ``self`` 

  

An exception is raised if ``self`` is immutable. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1,2,4,10,15,17]) 

sage: el[1] = 3 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

  

sage: with el.clone() as elc: 

....: elc[3] = 7 

sage: elc 

[1, 2, 4, 7, 15, 17] 

  

sage: with el.clone(check=False) as elc: 

....: elc[1:3] = [3,5,6,8] 

sage: elc 

[1, 3, 5, 6, 8, 10, 15, 17] 

""" 

self._require_mutable() 

self._list[key] = value 

  

def __delitem__(self, key): 

""" 

Remove the ith element of ``self`` 

  

An exception is raised if ``self`` is immutable. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingLists 

sage: el = IncreasingLists()([1, 4, 5, 8, 9]) 

sage: del el[3] 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

sage: with el.clone() as elc: 

....: del elc[3] 

sage: elc 

[1, 4, 5, 9] 

sage: with el.clone() as elc: 

....: del elc[1:3] 

sage: elc 

[1, 8, 9] 

""" 

self._require_mutable() 

del self._list[key] 

  

  

############################################################################ 

### Clonable Arrays of int ## 

############################################################################ 

cdef class ClonableIntArray(ClonableElement): 

""" 

Array of int with clone protocol 

  

The class of objects which are 

:class:`Element<sage.structure.element.Element>` behave as list of int and 

implement the clone protocol. See :class:`ClonableElement` for details 

about clone protocol. 

  

  

INPUT: 

  

- ``parent`` -- a :class:`Parent<sage.structure.parent.Parent>` 

- ``lst`` -- a list 

- ``check`` -- a boolean specifying if the invariant must be checked 

using method :meth:`check` 

- ``immutable`` -- a boolean telling wether the created element is 

immutable (defaults to ``True``) 

  

.. SEEALSO:: :class:`~sage.structure.list_clone_demo.IncreasingIntArray` 

for an example of usage. 

""" 

def __cinit__(self): 

self._len = -1 

self._list = NULL 

  

def __init__(self, Parent parent, lst, check = True, immutable = True): 

""" 

Initialize ``self`` 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: IncreasingIntArrays()([1,2,3]) 

[1, 2, 3] 

sage: IncreasingIntArrays()((1,2,3)) 

[1, 2, 3] 

  

sage: IncreasingIntArrays()(None) 

Traceback (most recent call last): 

... 

TypeError: object of type 'NoneType' has no len() 

  

sage: el = IncreasingIntArrays()([3,2,1]) 

Traceback (most recent call last): 

... 

ValueError: array is not increasing 

  

sage: el = IncreasingIntArrays()([1,2,4]) 

sage: list(iter(el)) 

[1, 2, 4] 

sage: list(iter(IncreasingIntArrays()([]))) 

[] 

  

You are not supposed to do the following (giving a wrong list and 

desactivating checks):: 

  

sage: broken = IncreasingIntArrays()([3,2,1], False) 

""" 

cdef int i 

self._parent = parent 

  

if self._list is not NULL: 

raise ValueError("resizing is forbidden") 

self._alloc_(len(lst)) 

for i from 0 <= i < self._len: 

self._list[i] = lst[i] 

  

self._is_immutable = immutable 

if check: 

self.check() 

  

cpdef _alloc_(self, int size): 

""" 

Allocate the array part of ``self`` for a given size 

  

This can be used to initialize ``self`` without passing a list 

  

INPUT: ``size`` - an int 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([], check=False) 

sage: el._alloc_(3) 

sage: el._setitem(0, 1); el._setitem(1, 5); el._setitem(2, 8) 

sage: el 

[1, 5, 8] 

sage: copy(el) 

[1, 5, 8] 

  

TESTS:: 

  

sage: el._alloc_(-1) 

Traceback (most recent call last): 

... 

AssertionError: Negative size is forbidden 

""" 

assert size >= 0, "Negative size is forbidden" 

self._is_immutable = False 

self._list = <int *>check_reallocarray(self._list, size, sizeof(int)) 

self._len = size 

  

def __dealloc__(self): 

sig_free(self._list) 

self._len = -1 

self._list = NULL 

  

def _repr_(self): 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: IncreasingIntArrays()([1,2,3]) 

[1, 2, 3] 

""" 

return '['+', '.join(["%i"%(self._list[i]) for i in range(self._len)])+']' 

  

def __nonzero__(self): 

""" 

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: IncreasingIntArrays()([1,2,3]).__nonzero__() 

True 

sage: IncreasingIntArrays()([]).__nonzero__() 

False 

""" 

return self._len != 0 

  

def __len__(self): 

""" 

Returns the len of ``self`` 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: len(IncreasingIntArrays()([1,2,3])) 

3 

""" 

return self._len 

  

def __iter__(self): 

""" 

Iterate over the items of self. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: I = IncreasingIntArrays()(range(5)) 

sage: I == list(range(5)) 

False 

sage: list(I) == list(range(5)) # indirect doctest 

True 

""" 

return iter(self.list()) 

  

cpdef list list(self): 

""" 

Convert self into a Python list. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: I = IncreasingIntArrays()(range(5)) 

sage: I == list(range(5)) 

False 

sage: I.list() == list(range(5)) 

True 

sage: I = IncreasingIntArrays()(range(1000)) 

sage: I.list() == list(range(1000)) 

True 

""" 

cdef int i 

cdef list L = <list> PyList_New(self._len) 

cdef object o 

for i from 0<=i<self._len: 

o = PyInt_FromLong(self._list[i]) 

Py_INCREF(o) 

PyList_SET_ITEM(L, i, o) 

return L 

  

def __getitem__(self, key): 

""" 

Returns the ith element of ``self`` 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,3]) 

sage: el[1] 

2 

sage: el[1:2] 

[2] 

sage: el[4] 

Traceback (most recent call last): 

... 

IndexError: list index out of range 

sage: el[-1] 

3 

sage: el[-1:] 

[3] 

sage: el[:] 

[1, 2, 3] 

sage: el[1:3] 

[2, 3] 

sage: type(el[:]) 

<... 'list'> 

sage: list(el) 

[1, 2, 3] 

sage: it = iter(el); next(it), next(it) 

(1, 2) 

""" 

cdef int start, stop, step, keyi 

cdef list res 

cdef slice keysl 

if isinstance(key, slice): 

keysl = <slice> key 

start, stop, step = keysl.indices(self._len) 

res = [] 

for i in range(start, stop, step): 

res.append(self._getitem(i)) 

return res 

keyi = <int> key 

if keyi < 0: 

keyi += self._len 

if 0 <= keyi < self._len: 

return self._list[keyi] 

else: 

raise IndexError("list index out of range") 

  

def __setitem__(self, int key, value): 

""" 

Set the ith element of ``self`` 

  

An exception is raised if ``self`` is immutable. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: elc[1] = 3; elc 

[1, 3, 4] 

sage: el[1] = 3 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

""" 

if 0 <= key < self._len: 

self._require_mutable() 

self._list[key] = value 

else: 

raise IndexError("list index out of range") 

  

cpdef object _getitem(self, int key): 

""" 

Same as :meth:`__getitem__` 

  

This is much faster when used with Cython and the index is known to be 

an int. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: IncreasingIntArrays()([1,2,3])._getitem(1) 

2 

""" 

if 0 <= key < self._len: 

return self._list[key] 

else: 

raise IndexError("list index out of range") 

  

cpdef _setitem(self, int key, value): 

""" 

Same as :meth:`__setitem__` 

  

This is much faster when used with Cython and the index is known to be 

an int. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: elc._setitem(1, 3); elc 

[1, 3, 4] 

sage: el._setitem(1, 3) 

Traceback (most recent call last): 

... 

ValueError: object is immutable; please change a copy instead. 

""" 

if 0 <= key < self._len: 

self._require_mutable() 

self._list[key] = value 

else: 

raise IndexError("list index out of range") 

  

def __contains__(self, int item): 

""" 

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: c = IncreasingIntArrays()([1,2,4]) 

sage: 1 in c 

True 

sage: 5 in c 

False 

""" 

cdef int i 

for i from 0 <= i < self._len: 

if item == self._list[i]: 

return True 

return False 

  

cpdef int index(self, int item) except -1: 

""" 

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: c = IncreasingIntArrays()([1,2,4]) 

sage: c.index(1) 

0 

sage: c.index(4) 

2 

sage: c.index(5) 

Traceback (most recent call last): 

... 

ValueError: list.index(x): x not in list 

""" 

cdef int i 

for i from 0 <= i < self._len: 

if item == self._list[i]: 

return i 

raise ValueError("list.index(x): x not in list") 

  

  

# __hash__ is not properly inherited if comparison is changed 

# see <http://groups.google.com/group/cython-users/t/e89a9bd2ff20fd5a> 

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,3]) 

sage: hash(el) # random 

-309690657 

sage: el1 = copy(el); hash(el1) 

Traceback (most recent call last): 

... 

ValueError: cannot hash a mutable object. 

""" 

if self._hash == 0: 

if not self._is_immutable: 

raise ValueError("cannot hash a mutable object.") 

else: 

self._hash = self._hash_() 

return self._hash 

  

# See protocol in comment in sage/structure/element.pyx 

cpdef int _cmp_(left, right) except -2: 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: elc == el # indirect doctest 

True 

  

:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el1 = IncreasingIntArrays()([1,2,4]) 

sage: el2 = IncreasingIntArrays()([1,2,3]) 

sage: el1 == el1, el2 == el2, el1 == el2 # indirect doctest 

(True, True, False) 

sage: el1 <= el2, el1 >= el2, el2 <= el1 # indirect doctest 

(False, True, True) 

""" 

cdef int i, minlen, reslen 

cdef ClonableIntArray rgt = <ClonableIntArray>right 

if left is right: 

return 0 

if left._list is NULL: 

if rgt._list is NULL: 

return 0 

else: 

return -1 

elif rgt._list is NULL: 

return 1 

if left._len < rgt._len: 

minlen = left._len 

reslen = -1 

elif left._len > rgt._len: 

minlen = rgt._len 

reslen = +1 

else: 

minlen = rgt._len 

reslen = 0 

for i from 0 <= i < minlen: 

if left._list[i] != rgt._list[i]: 

if left._list[i] < rgt._list[i]: 

return -1 

else: 

return 1 

return reslen 

  

cpdef ClonableIntArray __copy__(self): 

""" 

Returns a copy of ``self`` 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,4]) 

sage: elc = copy(el) 

sage: el[:] == elc[:] 

True 

sage: el is elc 

False 

  

We check that void lists are correctly copied:: 

  

sage: el = IncreasingIntArrays()([]) 

sage: elc = copy(el) 

sage: el is elc 

False 

sage: elc.__nonzero__() 

True 

sage: elc.is_mutable() 

True 

  

We check that element with a ``__dict__`` are correctly copied:: 

  

sage: IL = IncreasingIntArrays() 

sage: class myClass(IL.element_class): pass 

sage: el = myClass(IL, []) 

sage: el.toto = 2 

sage: elc = copy(el) 

sage: elc.toto 

2 

""" 

cdef ClonableIntArray res 

cdef type t = type(self) 

res = t.__new__(t) 

res._parent = self._parent 

if self: 

res._alloc_(self._len) 

for i from 0 <= i < res._len: 

res._list[i] = self._list[i] 

if HAS_DICTIONARY(self): 

res.__dict__ = self.__dict__.copy() 

return res 

  

cpdef check(self): 

""" 

Check that ``self`` fulfill the invariants 

  

This is an abstract method. Subclasses are supposed to overload 

``check``. 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone import ClonableArray 

sage: ClonableArray(Parent(), [1,2,3]) # indirect doctest 

Traceback (most recent call last): 

... 

NotImplementedError: this should never be called, please overload the check method 

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,4]) # indirect doctest 

""" 

raise NotImplementedError("this should never be called, please overload the check method") 

  

cpdef long _hash_(self) except? -1: 

""" 

Return the hash value of ``self``. 

  

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,3]) 

sage: el._hash_() # random 

-309711137 

sage: type(el._hash_()) == int 

True 

""" 

cdef long hv 

if self._list == NULL: 

hv = hash(None) 

else: 

hv = hash(tuple(self)) 

return hash(self._parent) + hv 

  

def __reduce__(self): 

""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: el = IncreasingIntArrays()([1,2,4]) 

sage: loads(dumps(el)) 

[1, 2, 4] 

sage: t = el.__reduce__(); t 

(<built-in function _make_int_array_clone>, 

(<type 'sage.structure.list_clone_demo.IncreasingIntArray'>, 

<sage.structure.list_clone_demo.IncreasingIntArrays_with_category object at ...>, 

[1, 2, 4], 

True, 

True, 

None)) 

sage: t[0](*t[1]) 

[1, 2, 4] 

""" 

# Warning: don't pickle the hash value as it can change upon unpickling. 

if HAS_DICTIONARY(self): 

dic = self.__dict__ 

else: 

dic = None 

return (sage.structure.list_clone._make_int_array_clone, 

(type(self), self._parent, self[:], 

self._needs_check, self._is_immutable, dic)) 

  

  

##### Needed for unpickling ##### 

def _make_int_array_clone(clas, parent, lst, needs_check, is_immutable, dic): 

""" 

Helpler to unpickle :class:`list_clone` instances. 

  

TESTS:: 

  

sage: from sage.structure.list_clone import _make_int_array_clone 

sage: from sage.structure.list_clone_demo import IncreasingIntArrays 

sage: ILs = IncreasingIntArrays() 

sage: el = _make_int_array_clone(ILs.element_class, ILs, [1,2,3], True, True, None) 

sage: el 

[1, 2, 3] 

sage: el == ILs([1,2,3]) 

True 

  

We check that element with a ``__dict__`` are correctly pickled:: 

  

sage: IL = IncreasingIntArrays() 

sage: class myClass(IL.element_class): pass 

sage: import __main__ 

sage: __main__.myClass = myClass 

sage: el = myClass(IL, []) 

sage: el.toto = 2 

sage: elc = loads(dumps(el)) 

sage: elc.toto 

2 

""" 

cdef ClonableIntArray res 

res = <ClonableIntArray> clas.__new__(clas) 

ClonableIntArray.__init__(res, parent, lst, needs_check, is_immutable) 

if dic is not None: 

res.__dict__ = dic 

return res 

  

  

  

cdef class NormalizedClonableList(ClonableList): 

""" 

List with clone protocol and normal form 

  

This is a subclass of :class:`ClonableList` which call a method 

:meth:`normalize` at creation and after any modification of its instance. 

  

.. SEEALSO:: :class:`~sage.structure.list_clone_demo.SortedList` for an 

example of usage. 

  

EXAMPLES: 

  

We construct a sorted list through its parent:: 

  

sage: from sage.structure.list_clone_demo import SortedLists 

sage: SL = SortedLists() 

sage: sl1 = SL([4,2,6,1]); sl1 

[1, 2, 4, 6] 

  

Normalization is also performed atfer modification:: 

  

sage: with sl1.clone() as sl2: 

....: sl2[1] = 12 

sage: sl2 

[1, 4, 6, 12] 

""" 

  

def __init__(self, Parent parent, lst, check = True, immutable = True): 

r""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import SortedList, SortedLists 

sage: SortedList(SortedLists(), [2,3,1]) 

[1, 2, 3] 

""" 

ClonableList.__init__(self, parent, lst, False, False) 

self.normalize() 

self._is_immutable = immutable 

if check: 

self.check() 

  

def __exit__(self, typ, value, tracback): 

r""" 

TESTS:: 

  

sage: from sage.structure.list_clone_demo import SortedList, SortedLists 

sage: l = SortedList(SortedLists(), [2,3,1], immutable=False); l 

[1, 2, 3] 

sage: l[1] = 5; l 

[1, 5, 3] 

sage: l.__exit__(None, None, None) 

False 

sage: l 

[1, 3, 5] 

""" 

self.normalize() 

return ClonableList.__exit__(self, typ, value, tracback) 

  

cpdef normalize(self): 

""" 

Normalize ``self`` 

  

This is an abstract method. Subclasses are supposed to overload 

:meth:`normalize`. The call ``self.normalize()`` is supposed to 

  

- call ``self._require_mutable()`` to check that ``self`` is in a 

proper mutable state 

- modify ``self`` to put it in a normal form 

  

EXAMPLES:: 

  

sage: from sage.structure.list_clone_demo import SortedList, SortedLists 

sage: l = SortedList(SortedLists(), [2,3,2], False, False) 

sage: l 

[2, 2, 3] 

sage: l.check() 

Traceback (most recent call last): 

... 

ValueError: list is not strictly increasing 

""" 

raise NotImplementedError("This should never be called, please overload the normalize method")