~philho/+junk/Scala

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
/*
 * Testing the base of the language (no GUI).
 * Loosely based on various tutorials,
 * like http://www.artima.com/scalazine/articles/steps.html
 * and http://jnb.ociweb.com/jnb/jnbDec2007.html
 * and some other articles/blog posts/mailing list messages...
 *
 * Code here is random, useless, sometime doing silly things, outputting gobbledigook.
 * It is just an exploration of the syntax, of some nice shortcuts and tricks, etc.,
 * trying to put them in various situations, with partial rewriting from origin to
 * better train my brain... ^_^
 * That's also a good test of my LexScala for Scintilla/SciTE!
 *
 * /* See how we can nest block comments! /* UTF-8 content: déjà vù */ */
 *
 * Warning! We must set Java file encoding to UTF-8 to see the Unicode chars in the output.
 * On the command line, on Windows, use:
 * set JAVA_OPTS=-Dfile.encoding=UTF-8
 * See http://stackoverflow.com/questions/1948044/printing-unicode-from-scala-interpreter
 * There might be issues in doing that, so encoding output is probably a better idea.
 *
 * Note: use -Xprint:typer option to scalac to see how it see the code...
 * Other options: -Ytyper-debug -Xlog-implicits
 * Should also try -XX:+DoEscapeAnalysis in some cases...
 * scalac -Xprint:parser -Yshow-trees
 * scalac -Ybrowse:parser
 * scalac -Xshow-phases
 * -Xcheckinit to check if a variable is used before it is used
 *
 * -g:vars (put all the symbols in the class file, for debugging)
 */
/* File history:
 *  1.00.000 -- 2011/xx/xx (PL) -- Perpetual update!
 *  0.00.000 -- 2010/08/26 (PL) -- Creation
 */
/*
Author: Philippe Lhoste <PhiLho(a)GMX.net> http://Phi.Lho.free.fr
Copyright notice: For details, see the following file:
http://Phi.Lho.free.fr/softwares/PhiLhoSoft/PhiLhoSoftLicense.txt
This program is distributed under the zlib/libpng license.
Copyright (c) 2010-2011 Philippe Lhoste / PhiLhoSoft
*/

// scalac will create the package path in the bin directory (where source is, or defined with the -d option of scalac),
// even if the file isn't in the corresponding path.
// Here, we declare the project's package and allow to see package protected objects at this level,
// including other packages: further package declarations will be relative to this one.
package org.philhosoft
// Declare the sub-package relative to the project's one (and see objects at this level)
package experiments
// That's a change in 2.8: previously, package org.myproject.tests would bring objects from all levels
// of this declaration into view. Now, it sees only the last package of the declaration.
// See http://www.artima.com/scalazine/articles/chained_package_clauses_in_scala.html for rationale.

// Illustrating import features...

// Several classes at once
import java.util.{ Date, Locale }
// All classes of the package: it uses _ instead of *
import java.util.regex._
// One class
import java.text.DateFormat
// Static import of all static methods, types, fields...
import java.text.DateFormat._
// Import whole package, allowing a short qualified name like zip.CRC32
import java.util.zip


// Testing ScalaDoc (and (SciTE and others) syntax highlighting!)
/** Just a typical main class as entry point of an application.
  * Silly class just exercice the Scala syntax and API.
  * @author PhiLho
  * @note End of ScalaDoc is supposed to be on last line of comment.
  * I don't like that much... OK, actually, I hate it, as I have to carry it
  * to any new line I can add! So I break this rule (that won't be the first, as I also use tabs...).
  */
// object -> singleton, class with only one instance
// Note that unlike Java, the object is public by default, and doesn't have to have the same name as the file.
// And several top-level public objects/classes can co-exist in the same file.
// scala -cp bin org.philhosoft.experiments.BaseExperiments
object BaseExperiments
{
	// Type inference: no need to declare the types
	val CONSTANT = "Scala" // Immutable - these are frequent, so all caps is usually avoided...
	var variable = 21      // Value can be changed
	// Semi-colons are optional as newline is (often) seen as end of statement (unless ambiguity, see (complex) rules.

	// Standard class entry point
	def main(args: Array[String])
	{
		// (Advanced) Auxilliary function: run the given function
		// only if this program was given no parameters
		// or the parameter naming one of the shown features
		def ?=>(feature: String)(f: => Unit)
		{
			if (args.isEmpty || args(0).toLowerCase == feature.toLowerCase)
			{
				f
			}
		}
		// Renamed because ??? have been added to 2.10
		// TODO: With an implicit, I can even write "CAS" ?=> classesAndSingletons

		// Call without parentheses as it takes no parameters.
		// Avoid this for methods with side effects (unlike what I do in this code! since println has a side effect).
		mandatoryMessage

		// Force limited scope
		?=>("props")
		{
			// Statically importing everything in Properties
			import scala.util.Properties._

			println("Home, sweet Home: " + scalaHome + " -> " +
					new java.io.File(scalaHome).getCanonicalPath)
			println(versionMsg)
			println(versionString)
			println(scalaPropOrElse("version.number", "unknown"))
			println(scalaPropOrElse("java.vm.version", "unknown"))
			println(System.getProperty("file.encoding")) // Java
		}

		=====("Arguments of this program")
		// Iterate on the array and apply the given function on each element
		args.foreach(println)

		?=>("warm")
		{
			=====("Warm up")
			// Alter variable, since it is mutable
			variable *= 2
			// A little concatenation of strings or toString results
			println("Nice to meet you, " + CONSTANT + "! (" + variable + ")")
			// Some function calling with parameters
			println("Min: " + minimal(variable, 314) + " " + regular(variable, 11))
			this showOff "Look, ma, no parentheses for method call with one parameter! ♥"
			// Calling function with variable number of arguments
			println("Vararg, no params: " + vararg())
			println("Vararg, 1 param: " + vararg(55))
			println("Vararg, n params: " + vararg(2, 3, 5, 7))
			// Named parameters: order can be changed
			println("Smallest is: " + regular(y = 314, x = 271))
			// Using default parameters
			complex(name = "Paul", age = 55)
			complex(sex = "F", name = "Claude", age = 17, interests = List("music", "dance"))
			// Can mix positional and named parameters
			complex(35, "Steven", interests = List("swimming"))

			// Beside the above classical identifiers, we can make wild ones
			// Chars
			var u_u = 'c'; val _da2 = '\u2620'; var déjà = '\uuu263C' // As much u as we want...
			// One identifier hard to use!
			// (SciTE shows it OK on one computer and not on another with the same font/settings... Mystery)
			// (Looks like I installed the Microsoft support for Asian scripts on one XP computer and not the other. Mystery solved!)
			val 愛_あい_♥ = "Love \uuu2661 = 愛 = あい"
			// Alphanumeric + underscore + operators
			val rude_%!^*# = "Be polite, please"
			// Pure operators
			val ^-^ = "Smiley ♪"
			// Anything between backquotes
			val `|(.)/` = "Wild! ♥"
			// Stuff
			val ↻↥↺ = "\u21BB\u21A5\u21BA " * 3
			// Using the identifiers
			val #=# = 愛_あい_♥ + " " + rude_%!^*# + " " + ^-^ + " " + `|(.)/` + " " +
					\u611B_\u3042\u3044_\u2665 + // This one is the same as the first one...
					\u21BB\u21A5\u21BA
			println("Unicode: " + #=#)

			// Using a semi-qualified class name
			val crc = new zip.CRC32
			crc update 42
			crc update 128
			Console.println("Zip's CRC32: " + crc.getValue); // Console isn't necessary but usable
		}

		// Use Java classes
		?=>("java")(frenchDate)

		// Array comprehension
		?=>("AC")(arrayComprehension)

		// Lists and tuples
		?=>("LAT")(listsAndTuples)

		// Sets and Maps
		?=>("SAM")(setsAndMaps)

		// Collection operations
		?=>("colop")(collectionOps)

		// Classes and Singletons
		?=>("CAS")(classesAndSingletons)

		// Traits and Mixins
		?=>("TAM")(traitsAndMixins)

		// User-defined operators or functions with strange names?
		?=>("op")(operators)

		// More on classes
		?=>("MC")(moreClasses)

		// Manipulating functions as first class objects
		?=>("fun")(manipulatingFunctions)

		// Pattern matching
		?=>("match")(patternMatching)

		// Exploring XML in Scala
		?=>("xml")(playingWithXML)

		// Misc
		?=>("misc")(miscellaneous)
	}

	// Method definitions: various styles

	// No parameters: no need for empty braces!
	// Note: it implies that this function MUST be called without braces,
	// unlike those with empty braces which can be called in both styles.
	def mandatoryMessage = println("Hello World!")
	// Minimal definition: return type is infered, no soft braces around code
	// Perfect for small pure functions (no side-effect)
	def minimal(x: Int, y: Int) = if (x < y) x else y
	// Regular definition: explicit return type, use soft braces even if there is only one line
	// Adding annotation as a strong hint that the function should be inlined.
	@inline def regular(x: Int, y: Int): Int =
	{
		if (x < y) x else y
	}
	// To define explicitely a method returning nothing (procedure)
	def showOff(m: String): Unit = println("Look: " + m)
	// Alternative syntax to methods returning Unit (ie. nothing):
	// Recommended by the style guide...
	def allSideEffect() // No ': Unit' nor '='
	{
		variable = 1961
		println("I changed 'variable'!")
	}
	// A method with a variable number of parameters (seen as an array)
	def vararg(arrayOfParams: Int*): Int =
	{
		var result = 0
		for (arg <- arrayOfParams) result += arg * arg
		result
	}
	// To show named parameters and default values
	def complex(age: Int, name: String, sex: String = "M", interests: List[String] = Nil)
	{
		// Using good old Java String format
		val sentence = "%1$s is a %2$d years old %3$s %4$s"
		val result = sentence format (name, age, if (sex == "M") "man" else "woman",
				if (interests == Nil) "without passions"
				else "interested in " + interests.mkString(", ")
		)
		println(result)
	}

	// Convenience method... Separator of sections both in source code (standing out visually) and in output
	def =====(message: String) = println("\n\n===== " + message)

	// The various steps of my exploration

	def frenchDate
	{
		=====("French date")
		// Using Java classes in various ways
		val now = new Date
		// Static import of all DataFormat content allows to use fields and functions as if they were part of this class
		val df = getDateInstance(LONG, Locale.FRANCE)
		// Style guide: "df format now" (infix notation) is OK as it has no side effects
		println("Current French date: " + (df format now))

		// We can rename classes. Good way to avoid namespace clashes (AWT's List vs. java.util.List for example).
		import java.util.{ Calendar => DateManager }
		// And even static methods!
		import java.util.Calendar.{ getInstance => getCalendar }
		// We can also import everything except one class
		import javax.swing.{ Action => _ /* discard */, _ }

		val cal: DateManager = getCalendar
		// Style guide: I wrote "cal setTime now" but it is discouraged because it isn't purely functional, it changes cal
		cal.setTime(now)
		cal.add(DateManager.YEAR, 10)
		// Style guide: don't use "cal getTime" (suffix notation),
		// it should be reserved as last operation of a chain of infix method calls, DSLs, last item of a line.
		val newTime = cal.getTime
		println("Future French date: " + (df format newTime))
	}

	def arrayComprehension
	{
		=====("Array Comprehension")
		// Array declaration and instanciation
		val message = new Array[String](3)
		// Fill the array
		message(0) = "One"; message(1) = "Two"; message(2) = "Three"

		// While loop
		var i = 0
		while (i < message.length)
		{
			println(". " + message(i))
			i += 1
		}

		// Idem, in functional style: => defines a canonical anonymous function
		message.foreach((msg: String) => println("- " + msg))
		// Type inference: omit the type
		message.foreach((msg) => println("+ " + msg))
		// Only one parameter: we can omit the parentheses
		message.foreach(msg => println("* " + msg))
		// Only one unchanged parameter: we can omit its declaration
		message.foreach(println(_))
		// Unaltered unique parameter, we can omit it altogether: ridiculously concise ;-)
		message.foreach(println)

		// With for loop
		for (msg <- message)
		{
			println(") " + msg)
		}

		// Numeric for loops
		for (i <- 1 to 3)
		{
			println("! " + message(i-1))
		}
		for (i <- 0 until 3)
		{
			println("% " + message(i))
		}

		// Simulating break
		// http://comments.gmane.org/gmane.comp.lang.scala.user/35817 - Partial loop run
		// Also http://stackoverflow.com/questions/2742719/how-do-i-break-out-of-a-loop-in-scala
		class Foo
		{
			var r = Foo.rand.nextInt(10)
			def isItOk() =
			{
				println("One more: " + r)
				r
			}
			def found() { println("Found!") }
		}
		object Foo
		{
			// Factory
			def apply(): Foo = new Foo
			val rand = new scala.util.Random(System.nanoTime)
		}
		class TT
		{
			def doStuff(f: Foo) { f.found }
		}
		val foos = for (i <- 0 until 50) yield Foo()
		val tt = new TT

		println("-- foreach")
		foos find (_.isItOk() == 1) foreach { tt doStuff _ }

		println("-- for")
		for (foo <- foos find (_.isItOk() == 1)) tt doStuff foo

		println("-- takeWhile 1")
		foos.takeWhile(_.isItOk() != 1).foreach(tt.doStuff(_))

		println("-- takeWhile 2")
		val res = foos.takeWhile(_.isItOk() != 1).foldLeft(0)(_ + _.r)
		println(res)
	}

	def listsAndTuples
	{
		=====("Lists and Tuples")
		// Making literal lists (using a generator)
		val shortList = List(1, 2, 3)
		val otherList = List(101, 102, 103, 104, 105)
		// Making a list with a range
		val longList = 55 to 77 by 2 toList
		// List concatenation
		val concatList = shortList ::: otherList
		println(shortList + " and " + otherList + " give " + concatList)
		// Cons operator (prepending)
		println("Cons: " + (55 :: shortList))
		println("Init with cons: " + (11 :: 22 :: 33 :: 44 :: Nil))

		=====("List Comprehension")
		val ll = "chill" :: "shell" :: "bell" :: "tell" :: "sell" :: Nil
		println(ll + " - (2): " + ll(2) + " - " + ll.length + " elements - " +
				(if (ll.isEmpty) "empty!" else "not empty"))
		println("Reversed: " + ll.reverse)
		println("First: " + ll.head)
		println("Last: " + ll.last)
		println("Without first: " + ll.tail)
		println("Without last: " + ll.init)
		println("Drop first 2: " + ll.drop(2))
		println("Drop last 2: " + ll.dropRight(2))

		// Using anonymous functions in calls: the long version
		println("Four letter words number: " + ll.count((s: String) => s.length == 4))
		// Using type inference
		println("Show four letter words: " + ll.filter(s => s.length == 4))
		// Getting rid of the unique parameter
		println("Show five letter words: " + ll.filter(_.length == 5))

//~ 		println("Remove four letter words: " + ll.remove(s => s.length == 4)) // Deprecated
		println("Remove four letter words: " + ll.filterNot(s => s.length == 4))
		// Using _ as wildcard/placeholder
		println("Remove five letter words: " + ll.filterNot(_.length == 5))
		println("Find 'tell': " + ll.exists(s => s == "tell"))
		println("All end with 'll': " + ll.forall(s => s.endsWith("ll")))
		println("All end with 'ell': " + ll.forall(s => s.endsWith("ell")))
		println("Map: " + ll.map(s => "\\" + s + "/"))
		println("Map with _: " + ll.map("\\" + _.toUpperCase + "/"))
		println
		println("Folding to sum: " + longList.foldLeft(0)((r, c) => r + c))
		// Idem, different syntax. Works because we use the parameters in the order they are given
		println("Folding to sum (bis): " + longList.foldLeft(0)(_ + _))
		// Sort on the first letter only
		// Also show anonymous function with two parameters
		// sort, toXxxCase are deprecated
//~ 		println("Sort: " + ll.sort((s, t) => s.charAt(0).toLowerCase < t.charAt(0).toLowerCase))
		println("Sort: " + ll.sortWith((s, t) => s.charAt(0).toLower < t.charAt(0).toLower))
		val zipped = ll zip otherList
		println("Zip: " + zipped)
		println("Min: " + ll.min)
		println("Other min: " + ll.reduceLeft((l, r) => if (r < l) r else l))
		// Also illustrates access to a member of a tuple
		println("Min of zip by number: " + zipped.min(Ordering.by((t: Tuple2[String, Int]) => t._2)))

		=====("Tuples")
		// Convenient to carry around several heterogenous values as a whole (eg. as return value)
		val oneTuple = (42, "H2G2")
		println("One simple tuple: " + oneTuple)
		val anotherTuple = (-0.42, 'H', 17, "SevenTeen")
		println("Another tuple: " + anotherTuple)

		// Declaring several variables with a tuple
		def sums(arrayOfParams: Int*) =
		{
			var sum = 0
			var sumSquares = 0
			for (arg <- arrayOfParams)
			{
				sum += arg
				sumSquares += arg * arg
			}
			(sum, sumSquares)
		}
		var (s1, s2) = sums(2, 4, 6, 8, 10)
		s1 *= 5
		println("Sums: " + s1 + " " + s2)
	}

	def setsAndMaps
	{
		// We can import anywhere in the code
		// The visibility of the imported classes is then limited to the current scope
		import scala.collection.mutable.{ HashSet, HashMap }

		=====("Sets")
		// Declare typed hash set
		val reSet = new HashSet[String]
		// Add one element
		reSet += "Reject"
		// Add two elements at once
		reSet += ("Refuse", "Refrain")
		println("HashSet " + reSet + " contains 'Remove'? " + reSet.contains("Remove"))

		=====("Maps")
		val numbers = new HashMap[Double, String]
		numbers += 3.1415926 -> "Pi"
		numbers += 2.71 -> "e"
		numbers += 1.414 -> "Square root of two"
		println("HashMap " + numbers + " -  " + numbers(2.71))

		val roman = Map("I" -> 1, "II" -> 2, "III" -> 3, "IV" -> 4)
		println("Roman " + roman + " - IV is " + roman("IV"))

		val heterogenous = Map(1 -> 11, 2 -> "Bah", 3 -> 'SomeSymbol,
				4 -> List("a" ,"b", 'c))
		val valuesAsList = heterogenous.valuesIterator.map(_.toString).toList
		println(valuesAsList)

		=====("ListBuffer")
		import scala.collection.mutable.ListBuffer
		val people = new ListBuffer[String]
		people += "Hendrix"
		people += "Lennon"
		people += "Morrison"
		println("People: " + people)
	}

	def collectionOps
	{
		=====("map over lists")

		val lst1 = List(1, 2, 3)
		val lst2 = List(11, 22, 33)

		println("List 1: " + lst1 + "\nList 2: " + lst2)

		// Map on list
		println("Simple map: " + lst1 + " -> " + lst1.map(x => x * 2))
		// Simpler syntax, implicit parameter
		println("Same: " + lst1.map(_ * 2))
		// Map makes nested lists
		def mapmult: Int => List[Int] = x => lst2.map(y => x * y)
		println("List mult: " + lst1 + " x " + lst2 + " -> " + lst1.map(mapmult))

		// Flattening
		println("Flattened list mult (1): " + lst1 + " x " + lst2 + " -> " +
				lst1.map(mapmult).flatten)
		println("Flattened list mult (2): " + lst1 + " x " + lst2 + " -> " +
				lst1.flatMap(mapmult))
		// Filtering
		println("Filtered list mult (1): " + lst1 + " x " + lst2 + " -> " +
				// Take odd members of lst1
				lst1.filter(_ % 2 == 1).flatMap(mapmult))

		// Martin Odersky: "My rule of thumb is, as soon as you have a flatMap in your chain of function applications,
		//   consider a for-expression instead. While it means exactly the same thing, it's almost always clearer."
		// With for comprehension
		val rLst = for (x <- lst1; y <- lst2; if x % 2 == 1) yield x * y
		println("Filtered list mult (2): " + rLst)

		=====("For (sequence) comprehension")

		// With conditional
		var oneOutOfTwo = for (i <- 1 to 17 if (i + 1) % 2 == 0) yield i
		println("One out of two: " + oneOutOfTwo)

		// Simple structure
		case class Result(name: String, note: Int)
		var zz = Result("Zazie", 15)
		var results = List(
			Result("Tom", 18),
			Result("Jo", 11),
			Result("Herbert", 17),
			zz
		)
		// Double loop with conditional
		for (r1 <- results;
				r2 <- results if r1 != r2 && r1.note > r2.note)
		{
			println(r1.name + " was better than " + r2.name)
		}
		println

		// Alternative syntax
		val allResults = for
		{
			r1 <- results
			r2 <- results if r1 != r2 && r1.note < r2.note
		} yield (r1, r2)
		allResults foreach { e => val (a, b) = e; println(a.name + " was worse than " + b.name) }
		println

		// Update of a variable with an immutable object
		print(zz.name + " note goes from " + zz.note)
		zz = zz.copy(note = 10)
		println(" to " + zz.note)

		=====("Collect first")
		val seq = Seq(('a', "Alphabet"), ('e', "Excalibur"), ('i', "Innocent"), ('o', "Opera") , ('u', "Universal"))

		// Walk a sequence and apply an action on the first item that matches the partial function
		seq collectFirst { case (letter, name) if letter % 3 == 0 => println(name) }
		val l = seq collectFirst { case (l, n) if n.length <= 5 => l }
		println(l)
	}

	def classesAndSingletons
	{
		=====("Classes and Singletons")
		// Parameters to the class are parameters to the main constructor. They are immutable and private.
		// They actually become fields accessible by methods of the class.
		@throws(classOf[IllegalArgumentException]) // Annotation documents the class (or def)
		class SimpleClass(count: Int, msg: String)
		{
			// Code in the body of the class itself is the code of the main constructor
			if (count < 0)
			{
				throw new IllegalArgumentException("Invalid 'count' parameter to SimpleClass: " + count)
			}

			// Secondary constructor, delegating to the main constructor with a default value
			def this(msg: String) = this(1, msg)

			// Accessing the constructor's parameters
			def show = for (i <- 1 to count) println(msg)
		}

		// With a mutable constructor parameter (which makes it public)
		// and  a public immutable parameter.
		class MoreClass(var count: Int, val msg: String)
		{
			println("In constructor of MoreClass")

			// Public by default
			var message = (msg + " ") * count
			private var msgCnt = msg

			def getMore =
			{
				count += 1
				msgCnt += "/" + count
				count
			}
			def getPrivate = msgCnt
			// Protected -> only sub-classes can call it, not classes of same package (unlike Java)
			protected def getMsg = msgCnt
			// Allow access to other classes of the package = package private
			private[experiments] def getDoubleMsg = msgCnt * 2
		}

		// Similar to super()
		class MinSubClass(msg: String) extends MoreClass(1, msg)
		// Yes, a class without body! Not that's much useful except to add a contructor...

		class SubClass(msg: String) extends MoreClass(3, msg)
		{
			println("In constructor of SubClass - " + getMsg)
		}

		// Singleton: class with only one instance
		// I take here the same name as a class to make a companion object
		object SubClass
		{
			// Equivalent to Java's static method
			def whoIAm = getClass.getName
			def mult(s: String) = s * 7
		}

		// Making Java-like bean
		import scala.reflect.BeanProperty
		class BeanClass(@BeanProperty var param: SubClass)
		{
			@BeanProperty var bear = param.getMore
		}

		import scala.reflect.BeanInfo
		@BeanInfo class Settings(var width: Int = 800, var height: Int = 600)

		// Private main constructor: we have to use the secondary constructor
		class PrivateClass private
		(
			a: Int,
			val b: String, // Public field
			c: Float
		)
		{
			def this(bah: String) = this(7, bah, 3.14f)
			def getVal = a * c
		}

		// Testing the above

		// The opportunity to show the try/catch syntax...
		try
		{
			val tc1 = new SimpleClass(-5, "Wrong!")
		}
		catch
		{
			case iae: IllegalArgumentException => println("SimpleClass with negative arg: " + iae.getMessage)
		}
		val tc2 = new SimpleClass(2, "Right")
		val tc3 = new SimpleClass("Right one")
		tc2.show
		tc3.show

		val mc = new MoreClass(7, "Bah")
		println(mc.getClass.getName + " " + mc.getMore)
		println("Can get public field: " + mc.message +
				" and, indirectly, private one: " + mc.getPrivate +
				" and the parameters, mutated: " + mc.count + " and immutable: " + mc.msg)

		val msc = new MinSubClass("Subway")
		println(msc.getClass.getName + " " + msc.getMore)

		val sc = new SubClass("Subversion")
		println(SubClass.whoIAm + " " + sc.getMore)
		println("Can get public field: " + sc.message +
				" and, indirectly, private one: " + sc.getPrivate +
				" and the parameters, mutated: " + sc.count + " and immutable: " + sc.msg)
		// Using the singleton's function
		println(SubClass mult "Ah ")

		val bc = new BeanClass(sc)
		// Access the fields JavaBean-style (useful to interact with Java libraries)
		val newSC = bc.getParam()
		val v = bc.getBear()
		bc.setBear(42)
		println("With bean: " + newSC.getPrivate + " - " + v + " / " + bc.bear)

		val pc = new PrivateClass("Private Parts")
		println(pc.getClass.getName + " " + pc.getVal + " " + pc.b)

		// More on exception handling, while I am at it...
		def doIt(a: Int, p: Int, va: Array[Int]): Int =
		{
			try
			{
				a / va(p)
			}
			catch
			{
				// Capture two cases
				case  _: IndexOutOfBoundsException | _: NullPointerException =>
					println("Bad parameter: " + p + " on " + va)
					0 // Value returned in case of exception
				case _: ArithmeticException =>
					println("Can't divide by zero!")
					-1
				case _ =>
					println("I wasn't excepting this one!")
					-2
			}
		}
		val vals = Array(0, 1, 3, 5, 7)
		println("# " + doIt(7, 0, vals))
		println("# " + doIt(7, 7, vals))
		println("# " + doIt(7, 1, null))
		println("# " + doIt(7, 4, vals))
	}

	def traitsAndMixins
	{
		// Viktor Klang: dont use normal vals in traits, prefer defs or lazy vals
		=====("Traits and Mixins")
		trait Moving
		{
			def move = "Swoosh"
		}
		class Car extends Moving
		{
			override def move = "Vroom"
		}
		trait Big extends Moving
		{
			override def move = super.move.toUpperCase
		}
		trait Fast extends Moving
		{
			override def move = super.move.map
					{ case c: Char => if (c.toUpper == 'O') 'i' else c }
		}

		// Defining with the trait, instanciating a class
		val deLorean: Moving = new Car
		println("See my vehicle go: " + deLorean.move)
		// Mixing another trait at instanciation time
		val truck: Moving = new Car with Big
		println("See my big vehicle go: " + truck.move)
		// The order of mixing is important:
		val supertruck = new Moving with Big with Fast
		val dragster = new Moving with Fast with Big
		println("Big and fast: " + supertruck.move)
		println("Fast and big: " + dragster.move)

		stackableTraitPattern
	}

	def stackableTraitPattern
	{
		// http://www.artima.com/scalazine/articles/stackable_trait_pattern.html
		println("-- Stackable trait pattern")
		// The base
		abstract class StringStack
		{
			def pop(): String
			def push(s: String): Unit
		}
		import scala.collection.mutable.ArrayBuffer
		class BaseStringStack extends StringStack
		{
			private val stack = new ArrayBuffer[String]
			def pop() = if (stack.isEmpty) "<empty>" else stack.remove(0)
			def push(s: String) { stack.insert(0, s) } // Alternative to =
		}
		// Unit test
		val stack = new BaseStringStack
		stack.push("Bottom")
		stack.push("Middle")
		stack.push("Top")
		println("Stack: " + stack.pop)
		println("Stack: " + stack.pop)
		println("Stack: " + stack.pop)
		// Now a trait, adding functionality
		trait UppercaseStack extends StringStack // extends implies this trait is usable only on such class
		{
			// Since we use super, we must mix this trait after
			// another trait or class providing a concrete definition of this class
			abstract override def push(s: String) = super.push(s.toUpperCase)
		}
		// Making a mix
		class UpperStack extends BaseStringStack with UppercaseStack
		// Using it (and stir a bit...)
		val uStack = new UpperStack
		uStack.push("Mixed Case")
		println("From upper stack: " + uStack.pop)
		// We can even mix as one shot!
		val duStack = new BaseStringStack with UppercaseStack
		duStack.push("Everybody Has Something To Hide Except Me And My Monkey")
		println("From upper stack: " + duStack.pop)
		// Make another trait
		trait FilteredStack extends StringStack // filtering given values
		{
			abstract override def push(s: String) =
			{
				if (s.matches("[A-Z].*"))
				{
					super.push(s)
				}
			}
		}
		// And mix the whole. Order is important...
		val ufStack = new BaseStringStack with UppercaseStack with FilteredStack
		ufStack.push("April"); ufStack.push("after life"); ufStack.push("45th"); ufStack.push("Gordon");
		println("Upper filtered stack: " + ufStack.pop + " | " + ufStack.pop + " | " + ufStack.pop + " | " + ufStack.pop)
		val fuStack = new BaseStringStack with FilteredStack with UppercaseStack
		fuStack.push("April"); fuStack.push("after life"); fuStack.push("45th"); fuStack.push("Gordon");
		println("Filtered upper stack: " + fuStack.pop + " | " + fuStack.pop + " | " + fuStack.pop + " | " + fuStack.pop)
	}

	def operators
	{
		=====("Custom operators")
		// Any method can be used as an infix operator
		val sentence = "Scala is a general purpose programming language";
		var splitted: Array[String] = null
		def showSplit = splitted mkString " | "
		// Using a method in a traditional way
		splitted = sentence.split(" ")
		println("Splitted with method: " + showSplit)
		// Using it as an operator
		splitted = sentence split " "
		println("Splitted with method as operator: " + showSplit)
		// Operator with more than one parameter
		splitted = sentence split (" ", 4)
		println("Splitted with method as multi-parameters operator: " + showSplit)

		// Defining a custom operator for classes
		class X(val value: Int)
		{
			// Infix (regular operator/method way)
			def +(y2: Ytwo) = value + y2.value
			// Another infix
			def +*(x: X) = new X(value * 2 + x.value * 3)
			// Prefix. Works only for + - ~ ! operators. No parameters
			def unary_- = if (value == 0) -1 else 1000/value // Whatever...
			// Postfix is any operator without parameters
			def ?? = 666 * value
			// Operator ending with a colon is right-associative:
			// its object must be on the right instead of being on the left
			def ?:?:(y2: Ytwo) = 1000 * y2.v + value
			// Utility
			override def toString = value.toString
		}
		class Ytwo(var value: Int)
		{
			val v = value
			value *= value
		}

		val x = new X(11)
		val y2 = new Ytwo(55)
		val r1 = x + y2 // We cannot do y2 + x with the current definitions!
		println("X + Y^2 = " + r1 + " for X=" + x + " and Y=" + y2.v)
		val r2 = -x
		println("-X = " + r2 + " for X=" + x)
		val r3 = x??; // Need semi-colon there
		println("X?? = " + r3 + " for X=" + x)
		val r4 = y2 ?:?: x
		println("Y ?:?: X = " + r4 + " for X=" + x + " and Y=" + y2.v)
		var r6 = new X(100) // Must be mutable
		val r5 = x +* r6
		println("X +* X2 = " + r5 + " for X=" + x + " and X2=" + r6)
		// Compiler magic, defines the +*= automatically
		r6 +*= x
		println("X2 +*= X = " + r6 + " for X2=100 and X=" + x.value)
	}

	def moreClasses
	{
		=====("More on classes")
		class AccessorsAndMutators(str: String, nb: Int)
		{
			private var mutableStr = str

			// Parameters above are private (and immutable).
			// We create ways to access and modify them.
			def msg = mutableStr // Acts as a read-only public variable
			// Assignment operator, allows to assign the public "variable", with checks and modifications
			def msg_=(s: String) = if (s.length > 1) mutableStr = s else mutableStr = "+" + s
			override def toString = mutableStr * nb
		}

		val tada = new AccessorsAndMutators("Tada!", 3)
		printf("Gist of message: %2$s and the message itself: %1$s\n", tada, tada.msg)
		tada.msg = "Daah."
		printf("Gist of message: %2$s and the message itself: %1$s\n", tada, tada.msg)
		tada.msg = "U"
		printf("Gist of message: %2$s and the message itself: %1$s\n", tada, tada.msg)

		// Another way, using special methods apply and update
		class Coll(size: Int)
		{
			val buffer = new Array[Double](size)

			@throws(classOf[IllegalArgumentException])
			@throws(classOf[NoSuchElementException])
			private def check(i: Int) =
			{
				if (i < 0) throw new IllegalArgumentException
				if (i >= size) throw new NoSuchElementException
			}
			def apply(i: Int): Double =
			{
				check(i)
				return buffer(i)
			}
			def update(i: Int, value: Double) =
			{
				check(i)
				buffer(i) = value
			}
		}
		val coll = new Coll(10)
		// Setting
		coll(8) = 3.1415926535897932384
		coll(4) = 2.71828182845904523536
		// Getting
		println("Numbers: " + coll(4) + " " + coll(8))

		// A function in Scala is an object. Which implements the apply method.
		// apply()  allows 'magically' to use the obj(x) notation.
		object Doubler // No constructor
		{
			def apply(n: Int) = n * 2
			def apply(n: Float) = n * 2
			def apply(n: String) = n * 2
		}
		println("Doubler: " + Doubler(11) + " " + Doubler(3.14159F) + " " + Doubler("Single "))

		// Using apply to make factories
		class Fact(val fact: String)
		{
			def apply(str: String) = { println("Fact class " + str); new Fact(str) }
			override def toString = "Fact: " + fact
		}
		object Fact
		{
			def apply(str: String) = { println("Fact object " + str); new Fact(str) }
		}

		println("Making objects")
		val f1 = new Fact("One")
		val f2 = f1("Two")
		val f3 = Fact("Three")
		println(f1 + " " + f2 + " " + f3)

		// Type aliasing
		type ArrayOfFacts = Array[Fact]
		var aof: ArrayOfFacts = Array(Fact("F1"), Fact("F2"), Fact("F3"))
		println("Array of facts: " + (aof mkString ", "))

		// Implicit conversion of types
		class OtherFact(val fact: String)
		{
			override def toString = "Other Fact: " + fact
		}
		def usingOtherFact(f: OtherFact) = println(f)
		// If I call usingOtherFact(new Fact("Homer likes donuts")) here, I get an error
		// So I make a conversion
		implicit def f2f(f: Fact) = new OtherFact("Other - " + f.fact)
		usingOtherFact(new Fact("Homer likes donuts"))
	}

	def manipulatingFunctions
	{
		=====("Manipulating functions")
		// Several ways to define a function. Return types can be omitted here, but it is nicer to be explict
		// Classical - actually, that's a method
		// See http://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala
		def d_+(str: String, n: Int): String = ("+" * n) + str
		// As a variable with an anonymous function. Return type cannot be specified (?), must be inferred
		val d_- = (str: String, n: Int) => ("-" * n) + str
		// Idem, with explicit type on the variable. Allows to be explicit on the return type
		val df: (String, Int) => String = (str: String, n: Int) => ("f" * n) + str
		// Actually, no need to re-specify the parameter types
		val dF: (String, Int) => String = (str, n) => ("F" * n) + str
		// Note: style guide discourage above style for function values (d_-). They prefer either:
		// - same syntax within a block, highlighting the functional nature of the variable
		val d1 = { (str: String, n: Int) => ("1" * n) + str }
		// - other syntax, with anonymous parameters. Seems to work only with the simplest expressions...
		// We cannot change the parameter order...
		val dx: (String, Int) => String = { "x" + _ + _ }

		//~ val f4: (Int, Int) => Int = {_+_} // Obscene emoticon... :-)

		// A function using functions as parameter
		def decorate(str: String, n: Int, fun: (String, Int) => String) = fun(str, n)

		println("Decorating with +: " + decorate("Plus", 7, d_+))
		println("Decorating with -: " + decorate("Minus", 6, d_-))
		println("Decorating with f: " + decorate("Eff", 5, df))
		println("Decorating with F: " + decorate("EFF", 4, dF))
		println("Decorating with 1: " + decorate("One", 3, d1))
		println("Decorating with x: " + decorate("Ixe", 2, dx))
		println("Decorating with anonymous function: " +
				decorate("Anon", 3, (s: String, i: Int) => s + i + s))

		// Canonical definition, as object
		val f1 = new Function1[Int, Int]
		{
			def apply(x: Int) = x * 2
		}
		// Using case statements to handle anonymous parameters
		val f2: Int => Int =
		{
			case even if even % 2 == 0 => even + 1
			case odd => odd * 2
		}

		// Implicit anonymous functions
		// From http://www.scala-lang.org/node/43
		// The expressions in the left column are each function values which expand to the anonymous functions on their right.
		/*
		_ + 1                  x => x + 1
		_ * _                  (x1, x2) => x1 * x2
		(_: int) * 2           (x: int) => (x: int) * 2
		if (_) x else y        z => if (z) x else y
		_.map(f)               x => x.map(f)
		_.map(_ + 1)           x => x.map(y => y + 1)
		*/

		// Manipulating a block (a function without parameters!)
		def measureTime(block: => Unit)
		{
			val start = System.nanoTime()
			// Running the block
			block
			val end = System.nanoTime()
			printf("Block ran in %f milliseconds\n", (end - start) / 1000000.0)
		}
		measureTime
		{
			var r = 0
			(1 to 100).foreach { n => r += r * n }
		}

		// Making a closure: a function enclosing a parameter
		def repeat(n: Int)(block: => Unit) = (1 to n).foreach { _ => block }
		repeat(3)
		{
			println("Loop")
		}
		// Partially applied function (missing the block part)
		val loop3 = repeat(3)_ // The trailing underscore marks not to run the function
		loop3
		{
			println("Loooop!")
		}
	}

	def patternMatching
	{
		=====("Pattern matching")
		// Class used specifically for pattern matching, having an automatic apply definition.
		// It can be seen as a simple structure (automatic accessor) with goodies thrown in
		// like no 'new' needed, default toString, equals and hashCode methods.
		// http://www.scala-lang.org/node/258 - http://markthomas.info/blog/?p=128
		// Gotcha: case classes cannot extend other case classes (well, should not? used to be restricted but it was lifted).
		// But they can extend normal classes and normal classes can inherit from case classes
		// (but they should be used as leaf nodes in a class hierarchy).
		// More importantly, case classes become implicitly abstract if they inherit an abstract member
		// which is not implemented. http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4
		case class Death(age: Int, reason: String)

		import java.awt.Color

		// Take anything to illustrate the process, can be more specialized!
		def nameMatching(something: Any) = something match
		{
			// Match on type
			case n: Int => "Integer: " + n
			case _: Char | _: Byte => "Some char or byte: " + something
			case d: Double => "Double: " + d
			case s: String => "Some string: " + s
			// Match on a precise kind of tuple
			case (x, 8) => "Tuple - first: " + x + " followed by eight"
			// Using a guard
			case (x: Int, y: Int) if (x > y) => "Tuple - first: " + x + " greater than second: " + y
			case (x, y) => "Other tuple - first: " + x + ", second: " + y
			// Match on object (case class)
			case Death(age, reason) if (age < 18) => "Passed away too young (" + age + ") from " + reason
			case Death(age, reason) => "Adult of " + age + " died from " + reason
			// Classes not case class much use match on type
			case c: Color =>
				// We can have several lines per case
				def roundPercent(v: Int) = math.ceil(v / 25.5) * 10.0
				val r = roundPercent(c.getRed)
				val g = roundPercent(c.getGreen)
				val b = roundPercent(c.getBlue)
				"A color of " + r + "% of red, " + g + "% of green and " + b + "% of blue -> " + c
			// Null catching
			case null => "I want something to dissect!"
			// Match anything, the "default"
			case _ => "I wasn't expecting this one!"
		}
		// Actually, make a specialized version, to avoid a warning on list:
		// warning: An Array will no longer match as Seq[_].
		def listMatching(something: List[_]) = something match
		{
			// Match on list pattern
			case h :: 11 :: t => "List - head: " + h + " followed by eleven, tail: " + t
			case h :: 42 :: t => "List - head: " + h + " followed by forty-two, tail: " + t
			case h :: t => "Other list - head: " + h + ", tail: " + t
			case _ => "Whatever"
		}

		val b: Byte = 0x42
		println(nameMatching(55))
		println(nameMatching('c'))
		println(nameMatching(b))
		println(nameMatching(2.71))
		println(nameMatching(3.14159F))
		println(nameMatching("Doh!"))
		println(nameMatching((1, 8)))
		println(nameMatching((8, 1)))
		println(nameMatching(("Last", "First")))
		println(nameMatching(new Death(11, "fall")))
		println(nameMatching(Death(27, "drowning"))) // No need for 'new'!
		println(nameMatching(new Color(127, 200, 255)))
		println(nameMatching(null))
		println(nameMatching(this))

		println(listMatching(7 :: 11 :: 666 :: 717 :: Nil))
		println(listMatching(List(7, 42, 717, 666)))
		println(listMatching("Ah" :: "Ooh" :: "Bah" :: Nil))
		println(listMatching(Nil))

		=====("Extractor objects")
		// http://www.scala-lang.org/node/112
		// TODO
	}

	def playingWithXML
	{
		def -----(message: String) = println("\n--- " + message)

		=====("XML in Scala")
		-----("Literal XML in Scala code")

		// Taking some real XML (altered) for testing
		val xmlFragment =
    <jnlp spec="1.0+" codebase="http://my.site/" href="gah/Some.jsp">
      <information>
        <vendor>My Site</vendor>
        <description>Java Web Start for my site</description>
        <description kind='short'>JWS/site</description>
        <icon kind='splash' href='gah/img/splash.png'/>
        <offline-allowed/>
        <title>My site is Rich!</title>
      </information>
      <security>
        <all-permissions/>
      </security>
          <!-- Funny indentation here... Seen as text. -->
            <dummy>For test only</dummy>
    </jnlp> // Must be completely closed

		// It is interpreted: single quotes becomes double quotes, self-closing tags becomes empty tags...
		println(xmlFragment)

		-----("Accessing nodes and attributes")
		// Using the projection function to get an element at first level
		println("Dummy node: " + (xmlFragment \ "dummy") + " -> " + (xmlFragment \ "dummy").text)
		// Going deeper
		println("Title: " + (xmlFragment \\ "title") + " -> " + (xmlFragment \\ "title").text)
		// Getting an attribute of the second description element
		println("Short desc: " + ((xmlFragment \\ "description")(1) \ "@kind") +
				" -> " + (xmlFragment \\ "description")(1).text)

		-----("Pattern matching")
		xmlFragment match
		{
			case <jnlp>{topTags @ _*}</jnlp> =>
			{
				for (info @ <information>{_*}</information> <- topTags)
				{
					println("Information: " + info.text)
				}
			}
			case _ => println("Oops, no match of jnlp")
		}

		-----("From and to XML")
		import scala.xml.{ Node, NodeSeq, XML }

		class JNLPInfo(
			val vendor: String,
			val title: String,
			val description: String,
			val icon: String,
			val offline: Boolean
		)
		{
			override def toString = "JNLP Info: vendor " + " \"" + title + " \"" +
					"\n\"\"\"" + description + "\"\"\"\n" + icon + " (" + offline + ")\n"

			val ix = <foo>Foo</foo><foo>Bar</foo><foo>Baz</foo>; // ; or empty line needed here
			val cx = // Tabs are keept as is, but the first one is eaten
		<enclosing>
			<boo>{ix}Ah! {CONSTANT}</boo>
			<boo>{val x = <sc/>; x}</boo>{/* XML in code inside XML... */}
			<boo>{
				(1 to 17 by 2).toList.map(i => <sub-boo>Item #{i}</sub-boo>)
			}</boo>
			<matching>
				<boo kind="moo">Cow</boo>
				<deep><boo kind="moo">DeepCow</boo></deep>
				<deep level="very"><other><boo kind="moo">DeepCow</boo></other></deep>
				<deep level="very"><other><boo kind="moo" empty="true"/></other></deep>
			</matching>
		</enclosing>

			def toXML =
			{
<information>
  <!-- This is the vendor -->
  <vendor>{vendor}</vendor>
  <description>{description}</description>
  <icon kind="splash" href={"http://" + vendor + ".com/" + icon}/>
    {for (x <- 1 to 5) yield // Expressions are allowed!
		<ref>{"x" * x}\n</ref>
	}
  {if (offline) <offline-allowed/>}
  <title>{title}</title>
  {cx}
</information>
			}
		}
		// Companion object
		object JNLPInfo
		{
			def fromXML(node: Node): JNLPInfo =
			{
				val icon = node \ "icon" \ "@href"
				val off = node \ "offline-allowed"
				new JNLPInfo(
					(node \ "vendor").text,
					(node \ "title").text,
					(node \ "description").text,
					icon.text,
					off != NodeSeq.Empty
				)
			}
		}
		val jnlpInfo = new JNLPInfo(
			vendor = "Moo",
			title = "The cow is hard",
			description = "Silly bad pun",
			icon = "moo.png",
			offline = true
		)
		println("-> JNLPInfo: " + jnlpInfo)
		val jnlpXML = jnlpInfo.toXML
		println("-> JNLPInfo to XML: " + jnlpXML + "\n")
		// Getting information tag and its sub-tags
		val otherInfo = xmlFragment \\ "information"
		val jo = JNLPInfo.fromXML(otherInfo.head)
		println("-> JNLPInfo from XML: " + jo)

		// Back to pattern matching
		println("-> Matching 1")
		for (node <- jnlpInfo.cx \\ "boo") node match
		{
			case node @ <boo>{_*}</boo> if
					node.attribute("kind").getOrElse("").toString == "moo" =>
			{
				println("Matching node: " + node)
			}
			case _ => Unit
		}
		println("-> Matching 2")
		(jnlpInfo.cx \\ "deep").head match
		{
			case <deep>{node @ _*}</deep> =>
			{
				println("Matching node: " + node)
			}
			case _ => Unit
		}
		println("-> Matching 3")
		// deep[@level='very']/other/foo[@kind='moo' and not(text())]
		import xml.Text
		val xpath =
		(
			(jnlpInfo.cx \\ "deep"
					filter (_ \ "@level" contains Text("very"))
			)
			\ "other" \ "boo" filter (el =>
					(el \ "@kind" contains Text("moo")) &&
					el.text == "")
		)
		println(xpath)

		// Not active, as this code must be working without file dependency...
//~ 		XML.saveFull("Moo.xml", jnlpXML, "UTF-8", true, null)
//~ 		val xmlFromFile = XML.loadFile("Moo.xml")
	}

	def miscellaneous
	{
		def -----(message: String) = println("\n--- " + message)

		=====("Miscellaneous")
		-----("Multiline and raw strings")

		val lsd =
"""
Picture yourself in a boat on a river with tangerine trees
And marmalade skies.
Somebody calls you, you answer quite slowly, a girl with
Kaleidoscope eyes.
"""
		println("Multiline strings: " + lsd + "...")
		// We can indent, for those liking that:
		val code1 = """	|  if (bFoo) {
						|    doStuff();
						|  }"""
		// or by using another marker:
		val code2 = """	§  if (bFoo) {
						§    doStuff();
						§  }"""
		println(code1.stripMargin)
		println(code2 stripMargin '§')
		// Only Unicode escapes are allowed here, probably substitued in an earlier compiler pass
		val mls = """|\n|\t|\|\\|\x22|\u00A4|"|""|"""
		println("Raw string: " + mls)

		// Trick: check a bunch of lines and tell if there is one line containing a string followed by any line
		// then a line containing another string
		{
			import io.Source

			def check(lineSource: Source, s1: String, s2: String) =
			(
				lineSource.
						getLines.
						sliding(3).
						exists // Checks if at least one predicate occurence is true
						{
							case List(l1: String, _, l3: String) => l1.contains(s1) && l3.contains(s2)
							case _ => false
						}
			)
			val ls = Source.fromString(lsd)

			println("Checking lyrics (boat, girl): " + check(ls, "boat", "girl"))
			println("Checking lyrics (tree, eye): " + check(ls, "tree", "eye"))
		}

		-----("Dumping bytes in hexa")

		def dumpBytesToHex(bytes: Seq[Byte]) = bytes.map(b => "%02X".format(b)).mkString
		def dumpStringToHex(string: String) = dumpBytesToHex(string.getBytes)
		println("Showing bytes in hex: " + dumpStringToHex(mls))

		-----("A cool string function: splitAt")

		{
			val ymd = "yyyyMMdd"
			val (y, md) = ymd splitAt 4
			val (m, d) = md splitAt 2
			println("From " + ymd + " to " + y + "-" + m + "-" + d)

			val ny = try { y.toInt } catch { case _ => 2010 }
			println("Year: " + ny)
		}

		-----("Using regular expressions")

		{
			// Raw strings shine here, as there is no need to double the backslashes
			val re = """\d+\.\d+\.\d+""".r
			val m = re findFirstMatchIn scala.util.Properties.versionMsg
			val posAndMatch = m match
			{
				case Some(m) => (m.start, m.matched)
				case None => (0, "")
			}
			println("Scala version: " + posAndMatch._2 + " found at " + posAndMatch._1)
		}
		{
			val re = """(\d{4})-(\d{4})""".r
			val m = re findFirstMatchIn scala.util.Properties.versionMsg
			val dates = m match
			{
				case Some(m) => (m.group(1), m.group(2))
				case None => ("", "")
			}
			println("Scala, from " + dates._1 + " to " + dates._2)
		}
		{
			val re = """id=(\d+):(\d+)""".r
			val s = """id=1:2
id=3:4
id=457:777"""
			val m = re.findAllIn(s).matchData.map(_.subgroups).toList
			println("Found " + m.mkString(", "))
		}

		-----("Option: Some or None")

		case class Contact(name: String, email: String)
		val peopleIKnow = List(
			Contact("Mario", "Mario@Nintendo.com"),
			Contact("Luigi", "Luigi@Nintendo.com")
		)
		val monstersIKnow = List(
			Contact("Yoshi", "Yoshi@Nintendo.com"),
			Contact("Toad", "Toad@Nintendo.com")
		)
		val occupations = Map(
			"plumber" -> peopleIKnow,
			"monster" -> monstersIKnow
		)
		println("TODO...?")

		// Option can be used to wrap null returned by a Java library

		// Returns null because the path doesn't point to an existing dir
		def listImaginaryFiles() = { (new java.io.File("/CannotExist")).list() }
		// Getting a default value
		val files1 = Option(listImaginaryFiles()) getOrElse Array("<no files>")
		println("Files 1:"); files1 foreach println
		// An alternative not creating an Option object just for this operation
		val files2 = listImaginaryFiles() match { case lf: Array[String] => lf; case _ => Array("<no files>") }
		println("Files 2:"); files2 foreach println

		-----("Lazy evaluation")

		class SomeMath(val x: Int, val y: Int)
		{
			val eagerVal =
			{
				println("I am eager")
				(x * 2, y * 2)
			}
			lazy val lazyVal =
			{
				println("I am lazy")
				(x * 5, y * 5)
			}
		}
		println("Instanciating")
		val compute = new SomeMath(11, 22)
		println("Getting values")
		println("Eager: " + compute.eagerVal)
		println("Lazy: " + compute.lazyVal)
		println

		-----("Bounded types")

		import scala.collection.mutable.HashMap

		// We can store any sub-class of a given class (upper type bounding)
		class MapOfComponentsU[V <: java.awt.Component] extends HashMap[String, V]
		val mocu = new MapOfComponentsU[javax.swing.JLabel]
		mocu += "Some name" -> new javax.swing.JLabel()

		// Or any super class of a given class (lower type bounding)
		class MapOfComponentsL[V >: javax.swing.JPanel] extends HashMap[String, V]
		val mocl = new MapOfComponentsL[java.awt.Container]

		-----("Enumerations with case objects")

		sealed trait Country { def capital: String; def name: String }
		case object FR extends Country { val name = "France";         val capital = "Paris" }
		case object DE extends Country { val name = "Germany";        val capital = "Berlin" }
		case object GB extends Country { val name = "United Kingdom"; val capital = "London" }
		case object ES extends Country { val name = "Spain";          val capital = "Madrid" }

		case class UnknownCountry(capital: String, name: String) extends Country

		def drinkHabits(country: Country): String =
		{
			country match
			{
				case FR => FR.name + " has wine"
				case DE => DE.name + " has beer"
				case ES => ES.name + " has sangria"
				case GB => ES.name + " has whisky"
				case UnknownCountry(_, c) => "I don't know " + c
			}
		}

		val countries = List(FR, FR, ES, GB, DE, DE, FR, ES, DE, GB);
		val someCountry = countries(7);
		println(someCountry + " -> " + drinkHabits(someCountry))
		val rnd = UnknownCountry("RND", "Random")
		println(rnd + " -> " + drinkHabits(rnd))

		// From the mailing list
		-----("Improved Scala Enumerations")

		object Planet extends Enumeration
		{
			protected case class Val(val mass: Double, val radius: Double)
					extends super.Val
			{
				def surfaceGravity: Double = Planet.G * mass / (radius * radius)
				def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity
			}

			implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]

			val G: Double = 6.67300E-11
			val Mercury = Val(3.303e+23, 2.4397e6)
			val Venus   = Val(4.869e+24, 6.0518e6)
			val Earth   = Val(5.976e+24, 6.37814e6)
			val Mars    = Val(6.421e+23, 3.3972e6)
			val Jupiter = Val(1.9e+27,   7.1492e7)
			val Saturn  = Val(5.688e+26, 6.0268e7)
			val Uranus  = Val(8.686e+25, 2.5559e7)
			val Neptune = Val(1.024e+26, 2.4746e7)
		}

		-----("A for loop made by Rex Kerr")

		// I don't understand it fully yet, but it is interesting and apparently fast
		// For loops (continuations) are much slower than the Java equivalent,
		// so it is recommended to use while loops instead.
		// This one tries to abstract the var i = 0; while (i < 100) { stuff; i += 1 } scheme.
		def cfor[@specialized T](zero: T, okay: T => Boolean, inc: T => T)(act: T => Unit)
		{
			var i = zero
			while (okay(i))
			{
				act(i)
				i = inc(i)
			}
		}
		var sum = 0
		cfor[Int](0, _ < 1000000, _+1) { sum += _ }
		println("Cfor Int Sum 1 = " + sum)
		sum = 0
		cfor[Int](0, _ < 1000000, _+1)
		{
			i =>
			{
				// This form is for more complex expressions!
				sum += i
			}
		}
		println("Cfor Int Sum 2 = " + sum)

		//### Resource manager by Rex Kerr
		def enclosed[C <: { def close() }](c: C)(f: C => Unit)
		{
			try { f(c) } finally { c.close() }
		}
		/* Example of use:
		enclosed(new FileInputStream(myFile))(fis =>
		{
			fis.read...
		})
		*/

		//### Smart trick from Nathan Hamblen (SPDE)
		-----("Adding a 'random' operator to lists")

		import scala.util.Random
		val rand = new Random

		// When requested, transforms a Seq to RichRandom
		implicit def seq2RichRandom[K](seq: Seq[K]) = new RichRandom(seq)

		class RichRandom[K](seq: Seq[K])
		{
			def random: K = seq((rand.nextFloat * seq.length).toInt)
		}

		-----("... and using symbols in place of strings")

		// Not sure yet of the usage...
		val stuff = List('Albert, 'Bruce, 'Caroline, 'Doris, 'Etienne, 'Francis, 'Gaelle)
		println("List of symbols: " + stuff)

		println("Some random items: " + stuff.random + ", " + stuff.random + ", " + stuff.random)

		// nextString doesn't seem very useful, making my own
		def nextAsciiString(length: Int): String = { List.fill(length)(rand.nextPrintableChar).mkString }
		val rnd1 = nextAsciiString(1)
		val rnd2 = nextAsciiString(5)
		val rnd3 = nextAsciiString(17)
		println("Some random strings: " + rnd1 + " " + rnd2 + " " + rnd3)
		println("In hexa: " + dumpStringToHex(rnd1) + " " + dumpStringToHex(rnd2) + " " + dumpStringToHex(rnd3))

		// Found an alternative
		def randomName(length: Int): String = util.Random.alphanumeric.take(length).mkString
		println("Other random strings: " + randomName(1) + " " + randomName(5) + " " + randomName(17))

		//### By Sciss (mailing list, "foreachwithindex", 2010-11-22
		-----("Loop with index")

		class RichIterable[A](it: Iterable[A])
		{
			def eachWithIndex(fun: (A, Int) => Unit)
			{
				var idx = 0
				val iter = it.iterator
				while (iter.hasNext)
				{
					fun(iter.next, idx)
					idx += 1
				}
			}
		}
		implicit def enrichIterable[A](it: Iterable[A]) = new RichIterable(it)

		Vector.fill(5)(math.random).
				eachWithIndex((num, idx) => println("At " + idx + ": " + num))

		// Standard alternative given by Jim McBeath
		// Slightly slower in 2.8.1 and 2.9.0
		println("or")
		Vector.fill(5)(math.random).zipWithIndex.foreach
		{
			case (num, idx) => println("At " + idx + ": " + num)
		}

		-----("Another implicit")

		// This allows to add a function to an existing class
		class Useless[T](a: Array[T])
		{
			def useless(n: Int) = a.length * n
		}
		// When needed, promotes array to Useless type
		implicit def array2useless[T](a: Array[T]) = new Useless(a)
		println("Implicit: " + Array(1, 2, 3, 4, 5).useless(10))

		// A generator of an arbitrary class (having default contructor)
		// By HamsterOfDeath
		class Something[T](implicit val m: Manifest[T])
		{
			def getOne(): T = { m.erasure.newInstance.asInstanceOf[T] }
		}
		val some = new Something[Random]
		val someRandom = some.getOne
		println("Rnd: " + someRandom.nextInt(5))

		//### Nice idea by Stefan Wagner
		-----("Rot13 implementation")
		def roll(c: Char, start: Char) = (((c - start + 13) % 26) + start).toChar

		def rot13(c: Char) = (c < 128, c.isLower, c.isUpper) match
		{
			case (true, true, _) => roll(c, 'a')
			case (true, _, true) => roll(c, 'A')
			case _ => c
		}
		val secret = "Mysterious Sentence, To Encode To ROT13!"
		val encoded = secret.map(rot13)
		println("ROT13: " + encoded)
		println("Was: " + encoded.map(rot13))

		// http://nicolaecaralicea.blogspot.com/2011/07/scala-get-taste-of-implicit-parameters.html
		-----("Implicit parameter")

		object ImplicitParameterizedQuickSort
		{
			implicit val lessIntOp = (x: Int, y: Int) => x < y
			implicit val lessStringOp = (x: String, y: String) => x < y

			def qsort[T](list : List[T])(implicit less : (T, T) => Boolean): List[T] =
			{
				list match
				{
					case List() => List() // Empty
					case h :: tail =>
						qsort(tail.filter(less(_, h))) ::: List(h) :::
								qsort(tail.filter(! less(_, h)))
				}
			}

			def Test()
			{
				// Using implicit parameter
				println(qsort(List(2, 4, 1, 6, 5)))
				println(qsort(List("violin", "piano","whistle", "guitar","saxophone")))
				// Explicit
				println(qsort(List(3.14, 1.41, 2.71, 299792.458, 365.2425))
						((x: Double, y: Double) => x < y))
			}
		}
		ImplicitParameterizedQuickSort.Test()

		//### By Jason Zaugg & Alex Zorab (scala-user, "Group seq elements in tuples", 2011-02-10
		-----("Group seq elements in tuples")
		val seq = Seq(1, 2, 3, 4, 5)
		// Keeping last element
		val seq1T = seq.grouped(2).map { case Seq(a, b) => (a, b); case Seq(u) => (u, u) }.toList
		println(seq + " -> " + seq1T)
		// Dropping last element: collect is a map that rejects items to matching in the partial function
		val seq2T = seq.grouped(2).collect { case Seq(a, b) => (a, b) }.toList
		println(seq + " -> " + seq2T)

		//### http://www.codecommit.com/blog/scala/implementing-groovys-elvis-operator-in-scala
		-----("Pass-by-name parameter")
		// A pass-by-name parameter is evaluated only if it is used
		def lazyEvalParam(c: Boolean, p: => String): String =
		{
			if (c) p
			else "I haven't used second parameter"
		}
		def giveParam(m: String): String = "Using " + m

		println("Evaluating param: " + lazyEvalParam(true, giveParam("First")))
		println("Not evaluating param: " + lazyEvalParam(false, giveParam("Second")))
	}

//~ 		-----("Wow... Lot of ways to express nothingness...")
//~ 		_, null, Null, Nil, Unit, None, Nothing, Option, Some, Either, Any, AnyVal, AnyRef
}