├── LICENSE ├── Makefile ├── README.md ├── c-sharp.txt ├── coffeescript.txt ├── cpp.txt ├── d.txt ├── entries.txt ├── f-sharp.txt ├── groovy.txt ├── harvest.py ├── haskell.txt ├── java.txt ├── javascript.txt ├── lua.txt ├── morph.css ├── morph.hs ├── morph.js ├── objective-c.txt ├── ocaml.txt ├── perl.txt ├── php.txt ├── python.txt ├── ruby.txt ├── scala.txt └── tcl.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Brian Chen 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | index.html : morph 2 | ./morph entries +python ruby javascript coffeescript perl php cpp +d java +scala ocaml +haskell lua > index.html 3 | 4 | morph : morph.hs 5 | ghc --make morph.hs 6 | 7 | clean : 8 | rm index.html morph 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **NOTE:** [Hyperpolyglot appeared on GitHub.](https://github.com/clarkgrubb/hyperpolyglot) I do not know if this will become obsolete yet. 2 | 3 | # Hyperpolymorph 4 | 5 | A flexible multi-language cheat sheet based on hyperpolyglot.org 6 | 7 | [**View on GitHub Pages**](http://betaveros.github.io/hyperpolymorph/) 8 | 9 | ## Why? 10 | 11 | - Sometimes, I want to compare languages that are on different sheets, like Python and Lua, or in completely different paradigms, like Python and Haskell and C++. It's not easy to do this with hyperpolyglot.org. 12 | - There are mistakes on hyperpolyglot.org which I've noticed but can't fix. Surely, others would have noticed this too. 13 | - I wanted an excuse to try out [Parsec](http://www.haskell.org/haskellwiki/Parsec). 14 | 15 | ## Running 16 | 17 | Parsing HTML files from hyperpolyglot.org into text files requires BeautifulSoup. Parsing the text files back into one HTML file requires Parsec. 18 | 19 | ## License 20 | 21 | The content of the cheat sheets themselves are licensed under [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/), as per hyperpolyglot.org, original content from [clarkgrubb](https://github.com/clarkgrubb). 22 | 23 | The scripts for parsing files and producing the HTML are released under the MIT license. Note that this is a very small part of the project. 24 | 25 | Still very much a WIP. I will tend to focus on languages proportional to how much I want to learn or use them, so it is quite unlikely my languages will develop the same as hyperpolyglot.org. Pull requests adding different languages are welcome, of course. 26 | -------------------------------------------------------------------------------- /c-sharp.txt: -------------------------------------------------------------------------------- 1 | `e version-used 2 | mono 2.10 (C# 4.0) 3 | `e show-version 4 | $ mcs --version 5 | `e implicit-prologue 6 | 7 | `e hello-world 8 | $ cat hello.cs 9 | 10 | using System; 11 | 12 | 13 | public class Hello { 14 | public static void Main() { 15 | Console.WriteLine("Hello, World!"); 16 | } 17 | 18 | } 19 | 20 | 21 | $ mcs hello.cs 22 | 23 | 24 | $ mono hello.exe 25 | `e file-suffixes 26 | Foo.cs 27 | none 28 | 29 | Foo.exe or Foo.dll 30 | 31 | although files are often named after a class they contain, this is not required 32 | `e block-delimiters 33 | { } 34 | `e statement-terminator 35 | ; 36 | `e top-level-statements 37 | 38 | `e end-of-line-comment 39 | // comment 40 | `e multiple-line-comment 41 | /* comment 42 | 43 | another comment */ 44 | `e local-variable 45 | int i; 46 | 47 | int j = 3; 48 | `e uninitialized-local-variable 49 | compiler prevents use of uninitialized local variable 50 | `e global-variable 51 | 52 | `e uninitialized-global-variable 53 | 54 | `e constant 55 | const int i = 7; 56 | `e assignment 57 | 58 | `e compound-assignment-arithmetic-string-logical-bit 59 | 60 | `e increment-and-decrement 61 | 62 | `e address 63 | 64 | `e dereference 65 | 66 | `e type-size 67 | 68 | `e address-arithmetic 69 | 70 | `e unique-pointer 71 | 72 | `e reference-count-pointer 73 | 74 | `e weak-pointer 75 | 76 | `e allocate-heap 77 | object i = 0; 78 | `e uninitialized-heap 79 | 80 | `e free-heap 81 | garbage collected 82 | `e null 83 | null 84 | `e coalesce 85 | string s1 = s2 ?? "was null"; 86 | `e boolean-type 87 | bool 88 | `e true-and-false 89 | true false 90 | `e falsehoods 91 | false 92 | `e logical-operators 93 | && || ! 94 | `e relational-operators 95 | == != < > <= >= 96 | `e integer-type 97 | sbyte 1 byte 98 | 99 | short 2 bytes 100 | 101 | int 4 bytes 102 | 103 | long 8 bytes 104 | `e unsigned-type 105 | byte 1 byte 106 | 107 | ushort 2 bytes 108 | 109 | uint 4 bytes 110 | 111 | ulong 8 bytes 112 | `e float-type 113 | float 4 bytes 114 | 115 | double 8 bytes 116 | `e fixed-type 117 | decimal 12 bytes 118 | `e arithmetic-operators 119 | + - * / % 120 | `e integer-division 121 | // evaluates to 2: 122 | 123 | 7 / 3 124 | `e integer-division-by-zero 125 | Syntax error if divisor is a constant. Otherwise throws System.DivideByZeroException 126 | `e float-division 127 | 7 / (float)3 128 | `e float-division-by-zero-dividend-is-positive-zero-negative 129 | float.PositiveInfinity 130 | 131 | float.NaN 132 | 133 | float.NegativeInfinity 134 | 135 | constants with same names defined in double 136 | `e power 137 | System.Math.Pow(2.0, 32.0); 138 | `e sqrt 139 | Math.Sqrt(2) 140 | `e sqrt-1 141 | double.NaN 142 | `e transcendental-functions 143 | using System; 144 | 145 | 146 | Math.Exp Math.Log none Math.Log10 147 | 148 | Math.Sin Math.Cos Math.Tan 149 | 150 | Math.Asin Math.Acos Math.Atan 151 | 152 | Math.Atan2 153 | `e transcendental-constants 154 | System.Math.E 155 | 156 | System.Math.PI 157 | `e float-truncation 158 | using System; 159 | 160 | 161 | (long)3.77 162 | 163 | Math.Round(3.77) 164 | 165 | Math.Floor(3.77) 166 | 167 | Math.Ceiling(3.77) 168 | `e absolute-value-and-signum 169 | System.Math.Abs(-7) 170 | 171 | System.Math.Abs(-7.77) 172 | `e integer-overflow 173 | modular arithmetic 174 | `e float-overflow 175 | float.PositiveInfinity 176 | `e float-limits-largest-finite-float-smallest-positive-float 177 | float.MaxValue 178 | 179 | float.Epsilon 180 | 181 | double.MaxValue 182 | 183 | double.Epsilon 184 | `e complex-construction 185 | 186 | `e complex-decomposition-real-and-imaginary-component-argument-absolute-value-conjugate 187 | 188 | `e random-number-uniform-integer-uniform-float-normal-float 189 | using System; 190 | 191 | 192 | Random rnd = new Random(); 193 | 194 | 195 | int i = rnd.Next(); 196 | 197 | double x = rnd.NextDouble(); 198 | none 199 | `e random-seed 200 | using System; 201 | 202 | 203 | Random rnd = new Random(17); 204 | `e bit-operators 205 | << >> & | ^ ~ 206 | `e binary-octal-and-hex-literals 207 | none 208 | 209 | 052 210 | 211 | 0x2a 212 | `e radix-convert-integer-to-and-from-string-with-radix 213 | 214 | `e string-type 215 | string 216 | `e string-literal 217 | "don't say \"no\"" 218 | `e newline-in-literal 219 | string literals can extend over multiple lines, but the newlines do not appear in the resulting string 220 | `e literal-escapes 221 | \a \b \f \n \r \t \v 222 | 223 | \\ \" \' 224 | 225 | \xhh \xhhhh \o \oo \ooo 226 | `e allocate-string 227 | string s = "hello"; 228 | 229 | string t = string.Copy(s); 230 | `e are-strings-mutable 231 | 232 | `e copy-string 233 | 234 | `e format 235 | string.Format("{0}: {1}", "Spain", 7) 236 | `e compare-strings 237 | "hello".CompareTo("world") 238 | `e concatenate-and-append 239 | "hello" + " world" 240 | `e replicate 241 | 242 | `e translate-case 243 | "hello".ToUpper() 244 | 245 | HELLO".ToLower() 246 | `e trim 247 | " hello ".Trim() 248 | `e pad 249 | 250 | `e number-to-string 251 | 14.ToString() 252 | 253 | 14.7.ToString() 254 | `e string-to-number 255 | byte.Parse("14") 256 | 257 | short.Parse("14") 258 | 259 | int.Parse("14") 260 | 261 | long.Parse("14") 262 | 263 | float.Parse("14") 264 | 265 | double.Parse("14") 266 | 267 | decimal.Parse("14") 268 | `e join 269 | System.String.Join(", ", names) 270 | `e split 271 | string[] names = "Bob Ned Amy".Split(' '); 272 | `e serialize 273 | 274 | `e string-length 275 | s.Length 276 | `e index-of-substring 277 | "hello".IndexOf("ll") 278 | `e extract-substring 279 | "hello".Substring(2, 2) 280 | `e character-type 281 | 282 | `e character-literal 283 | 284 | `e test-character 285 | 286 | `e regex-type 287 | 288 | `e character-class-abbreviations 289 | 290 | `e anchors 291 | 292 | `e lookahead-positive-negative 293 | 294 | `e match-test 295 | using System.Text.RegularExpressions; 296 | 297 | Regex regex = new Regex("ll"); 298 | 299 | bool isMatch = regex.IsMatch("hello"); 300 | `e case-insensitive-match-test 301 | 302 | `e modifiers 303 | 304 | `e substitution 305 | using System.Text.RegularExpressions; 306 | 307 | Regex r1 = new Regex("ll"); 308 | 309 | String s1 = r1.Replace("hello", "LL", 1); 310 | 311 | Regex r2 = new Regex("l"); 312 | 313 | String s2 = r2.Replace("hello", "L"); 314 | `e match-prematch-postmatch 315 | 316 | `e group-capture 317 | 318 | `e date-time-type 319 | System.DateTime 320 | `e current-date-time 321 | DateTime dt = DateTime.Now(); 322 | `e to-unix-epoch-from-unix-epoch 323 | long hundredM = 100 * 1000 * 1000; 324 | 325 | long sec = dt.ToFileTimeUtc() / hundredM; 326 | 327 | long epoch = sec - 1164444480; 328 | 329 | 330 | long ft = (epoch + 1164444480) * hundredM; 331 | 332 | Date dt2 = DateTime.FromFiltTimeUtc(ft); 333 | `e date-and-time-to-string 334 | 335 | `e format-date 336 | String s = "yyyy-MM-dd HH:mm:ss"); 337 | 338 | String s2 = dt.ToString(s); 339 | `e parse-date 340 | CultureInfo enUS = 341 | new CultureInfo("en-US"); 342 | 343 | 344 | DateTime dt2 = DateTime.ParseExact( 345 | "2011-05-03 17:00:00", 346 | "yyyy-MM-dd HH:mm:ss", 347 | enUS); 348 | `e date-subtraction 349 | 350 | `e add-duration 351 | 352 | `e date-parts 353 | 354 | `e time-parts 355 | 356 | `e declare-on-stack 357 | arrays must be allocated on heap 358 | `e declare-on-heap 359 | int[] a = new int[10]; 360 | `e free-heap 361 | garbage collected 362 | `e array-initialization-list 363 | int[] a = {1,2,3}; 364 | `e list-size 365 | a.Length 366 | `e lookup 367 | a[0] 368 | `e update 369 | 370 | `e out-of-bounds 371 | IndexOutOfRangeException 372 | `e copy 373 | 374 | `e as-function-argument 375 | 376 | `e iterate-over-elements 377 | foreach (string name in names) { 378 | `e sort 379 | 380 | `e list-name 381 | List 382 | `e list-declare 383 | using System.Collections.Generic; 384 | List l = new List(); 385 | 386 | `e list-size 387 | l.Count 388 | `e capacity-get-increase 389 | 390 | `e empty-test-and-clear 391 | 392 | `e lookup 393 | l[0] 394 | `e update 395 | 396 | `e out-of-bounds 397 | throws System.ArgumentOutOfRangeException 398 | `e index-of-element 399 | 400 | `e slice 401 | 402 | `e drop 403 | 404 | `e manipulate-back 405 | l.Add("hello"); 406 | 407 | l.RemoveAt(l.Count - 1); 408 | `e manipulate-front 409 | 410 | `e concatenate 411 | 412 | `e list-replicate 413 | 414 | `e copy 415 | 416 | `e array-as-function-argument 417 | 418 | `e array-iterate 419 | foreach ( string s in l ) { 420 | do something with s 421 | 422 | } 423 | `e iterate-over-indices-and-elements 424 | 425 | `e reverse 426 | 427 | `e sort 428 | 429 | `e dedupe 430 | 431 | `e membership 432 | 433 | `e intersection 434 | 435 | `e union 436 | 437 | `e relative-complement-symmetric-difference 438 | 439 | `e map 440 | 441 | `e filter 442 | 443 | `e min-and-max-element 444 | 445 | `e shuffle-and-sample 446 | 447 | `e zip 448 | 449 | `e declare-pair 450 | using System.Collections.Generic; 451 | 452 | KeyValuePair pr = new KeyValuePair("hello",5); 453 | 454 | System.Console.WriteLine("{0} {1}", pr.Key, pr.Value); 455 | `e lookup-pair-elements 456 | 457 | `e update-pair-elements 458 | 459 | `e declare-tuple 460 | 461 | `e lookup-tuple-elements 462 | 463 | `e update-tuple-elements 464 | 465 | `e tuple-size 466 | 467 | `e create-references-for-tuple-elements 468 | 469 | `e map-declaration 470 | using System.Collections.Generic; 471 | 472 | Dictionary dict = new Dictionary(); 473 | `e map-access 474 | dict.Add("hello", 5); 475 | 476 | dict["hello"] 477 | `e map-size 478 | dict.Count 479 | `e map-remove-element 480 | dict.Remove("hello"); 481 | `e map-element-not-found-result 482 | throws KeyNotFoundException 483 | in System.Collections.Generic 484 | `e map-iterate 485 | foreach ( KeyValuePair e in dict) { 486 | use e.Key and e.Value 487 | 488 | } 489 | `e declare-function 490 | 491 | `e define-function 492 | 493 | `e invoke-function 494 | 495 | `e define-static-class-method 496 | 497 | `e invoke-static-class-method 498 | 499 | `e overload-function 500 | yes 501 | `e default-argument 502 | use method overloading 503 | `e variable-number-of-arguments 504 | public static string concat(params string[] args) { 505 | return System.String.Join("",args); 506 | 507 | } 508 | 509 | string s = Concat.concat("Hello", ", ", "World", "!") 510 | `e named-parameters 511 | added in C# 4.0: 512 | 513 | static int BMI(int weight, int height) { 514 | return (weight * 703) / (height * height); 515 | 516 | } 517 | 518 | BMI(weight: 123, height: 64); 519 | 520 | BMI(height: 64, weight: 123); 521 | `e pass-by-value 522 | primitive types are always passed by value 523 | `e pass-by-reference 524 | objects and arrays are always passed by reference 525 | 526 | also out parameter 527 | `e pass-by-address 528 | none 529 | `e return-value 530 | 531 | `e no-return-value 532 | 533 | `e recursive-function 534 | 535 | `e lambda 536 | 537 | `e invoke-anonymous-function 538 | 539 | `e closure 540 | 541 | `e function-with-private-state 542 | 543 | `e function-as-value 544 | 545 | `e overload-operator 546 | public static Rational operator+(Rational a, Rational b) { 547 | return new Rational(a.num*b.denom + b.num *a.denom,a.denom*b.denom); 548 | 549 | } 550 | `e if 551 | if (i>0) { 552 | signum = 1; 553 | 554 | } else if (i==0) { 555 | signum = 0; 556 | 557 | } else { 558 | signum = -1; 559 | 560 | } 561 | `e dangling-else 562 | 563 | `e switch 564 | switch(i) { 565 | 566 | case 0: 567 | 0; 568 | break; 569 | 570 | case 1: 571 | 1; 572 | break; 573 | 574 | default: 575 | -1; 576 | break; 577 | 578 | } 579 | `e while 580 | int i = 0; 581 | 582 | while (i<10) { 583 | … 584 | i++; 585 | 586 | } 587 | `e for 588 | int i, n; 589 | 590 | for (i=1,n=1; i<=10; i++) { 591 | n *= i; 592 | 593 | } 594 | `e break 595 | 596 | `e break-out-of-nested-loops 597 | 598 | `e continue 599 | 600 | `e goto 601 | 602 | `e base-exception 603 | 604 | `e predefined-exceptions 605 | 606 | `e raise-exception 607 | throw new System.Exception("failed"); 608 | `e handle-exception 609 | try { 610 | throw new System.Exception("failed"); 611 | 612 | } catch (System.Exception e) { 613 | System.Console.WriteLine(e.Message); 614 | 615 | } 616 | `e define-exception 617 | 618 | `e re-raise-exception 619 | 620 | `e catch-all-handler 621 | 622 | `e multiple-handlers 623 | 624 | `e uncaught-exception-behavior 625 | 626 | `e error-message 627 | 628 | `e system-call-errno 629 | 630 | `e finally 631 | try { 632 | risky code 633 | 634 | } finally { 635 | perform cleanup 636 | 637 | } 638 | `e exception-specification 639 | no 640 | `e start-thread 641 | 642 | `e terminate-current-thread 643 | 644 | `e terminate-other-thread 645 | 646 | `e list-threads 647 | 648 | `e wait-on-thread 649 | 650 | `e lock 651 | 652 | `e create-message-queue 653 | 654 | `e send-message 655 | 656 | `e receive-message 657 | 658 | `e standard-file-handles 659 | 660 | `e printf 661 | System.Console.WriteLine("count: {0}", 7); 662 | `e read-from-file 663 | using System.IO; 664 | 665 | StreamReader sr = new StreamReader("/etc/passwd"); 666 | 667 | string line; 668 | 669 | while ((line = sr.ReadLine()) != null) { 670 | use line 671 | 672 | } 673 | `e write-to-file 674 | using System.IO; 675 | 676 | StreamWriter fout = new StreamWriter("/tmp/test3"); 677 | 678 | int i; 679 | 680 | for (i=0; i<10; i++) { 681 | fout.WriteLine(i.ToString()); 682 | 683 | } 684 | 685 | fout.Close(); 686 | `e file-exists-test-regular-test 687 | System.IO.File.Exists("/etc/hosts") 688 | `e file-size 689 | 690 | `e is-file-readable-writable-executable 691 | 692 | `e set-file-permissions 693 | 694 | `e copy-file-remove-file-rename-file 695 | 696 | `e csv 697 | 698 | `e json 699 | 700 | `e build-xml 701 | 702 | `e parse-xml 703 | 704 | `e parse-html 705 | 706 | `e build-pathname 707 | 708 | `e dirname-and-basename 709 | 710 | `e absolute-pathname 711 | 712 | `e iterate-over-directory-by-file 713 | 714 | `e glob-paths 715 | 716 | `e make-directory 717 | 718 | `e recursive-copy 719 | 720 | `e remove-empty-directory 721 | 722 | `e remove-directory-and-contents 723 | 724 | `e directory-test 725 | 726 | `e generate-unused-directory-name 727 | 728 | `e system-temporary-file-directory 729 | 730 | `e signature-of-main 731 | public class Foo { 732 | public static void Main(string[] args) { 733 | `e first-argument 734 | first command line argument 735 | `e environment-variable 736 | using System.Environment; 737 | 738 | string home = GetEnvironmentVariable("HOME"); 739 | 740 | SetEnvironmentVariable("EDITOR", "emacs"); 741 | 742 | SetEnvironmentVariable("EDITOR", null); 743 | `e iterate-through-environment-variables 744 | using System.Collections; 745 | 746 | using System.Environment; 747 | 748 | IDictionary env = GetEnvironmentVariables(); 749 | 750 | foreach (DictionaryEntry de in env) { 751 | use de.Key or de.Value 752 | 753 | } 754 | `e standard-library-name 755 | Base Class Library 756 | `e declare-namespace 757 | namespace foo { 758 | namespace bar { 759 | public class Baz { 760 | public const int ANSWER = 42; 761 | }; 762 | } 763 | 764 | } 765 | `e multiple-namespaces-per-file 766 | yes 767 | `e namespaces-map-to-directories 768 | no 769 | `e import-namespace 770 | using foo.bar; 771 | 772 | System.Console.WriteLine(Baz.ANSWER); 773 | `e import-part-of-namespace 774 | none 775 | `e import-symbol 776 | none 777 | `e import-static-symbol 778 | none 779 | `e import-position 780 | outside of class definitions 781 | `e using-a-symbol-that-hasn-t-been-imported 782 | using System.Console; 783 | 784 | WriteLine(foo.bar.Baz.ANSWER); 785 | `e application-environment 786 | 787 | `e multiple-installations 788 | 789 | `e package-manager 790 | 791 | `e type-synonym 792 | none 793 | `e enum 794 | public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN }; 795 | 796 | DayOfWeek d = DayOfWeek.TUE; 797 | `e struct-definition 798 | public class MedalCount { 799 | public string country; 800 | public int gold; 801 | public int silver; 802 | public int bronze; 803 | 804 | } 805 | `e struct-declaration 806 | MedalCount spain = new MedalCount(); 807 | `e struct-initialization 808 | no object literal syntax; define a constructor 809 | `e struct-member-assignment 810 | spain.country = "Spain"; 811 | 812 | spain.gold = 3; 813 | 814 | spain.silver = 7; 815 | 816 | spain.bronze = 4; 817 | `e struct-member-access 818 | int spain_total = spain.gold + spain.silver + spain.bronze; 819 | `e define-generic-type 820 | public class Foo { 821 | public A a; 822 | public Foo(A a) { 823 | this.a = a; 824 | } 825 | 826 | } 827 | `e instantiate-generic-type 828 | Foo f = new Foo("foo"); 829 | `e generic-function 830 | 831 | `e generic-array 832 | public class Bar { 833 | public C[] a; 834 | public Bar(C c) { 835 | this.a = new C[10]; 836 | } 837 | 838 | } 839 | `e value-parameter 840 | 841 | `e template-parameter 842 | 843 | `e template-specialization 844 | 845 | `e multiple-type-parameters 846 | 847 | `e generic-type-parameters 848 | 849 | `e template-parameters 850 | 851 | `e variadic-template 852 | 853 | `e semantics-of 854 | value comparison 855 | `e define-class 856 | public class Rational { 857 | public int num; 858 | public int denom; 859 | 860 | } 861 | `e class-definition-location 862 | 863 | `e constructor 864 | public Rational(int n, int d) { 865 | if (0 == d) { 866 | throw new System.Exception("zero denominator"); 867 | } 868 | if (d < 0) { 869 | this.num = -1 * n; 870 | this.denom = -1 * d; 871 | } 872 | else { 873 | this.num = n; 874 | this.denom = d; 875 | } 876 | 877 | } 878 | `e create-object 879 | Rational r = new Rational(7,3); 880 | `e destructor 881 | ~Rational() { 882 | perform cleanup 883 | 884 | } 885 | `e destroy-object 886 | none 887 | `e define-method 888 | public int Height() { 889 | return (System.Math.Abs(this.num) > this.denom) ? System.Math.Abs(this.num) : this.denom; 890 | 891 | } 892 | `e invoke-method 893 | r.Height(); 894 | `e define-class-method 895 | declare static in class definition 896 | `e invoke-class-method 897 | 898 | `e name-of-receiver 899 | this 900 | `e access-control 901 | access keywords available for methods and members: 902 | 903 | public class Foo { 904 | private int privateInt1; 905 | int privateInt2; 906 | protected int protectedInt; 907 | public int publicInt; 908 | 909 | } 910 | `e anonymous-class 911 | 912 | `e dynamic-dispatch 913 | declare as virtual in base class and override in derived class 914 | `e static-dispatch 915 | dispatch static by default; compiler error if same method defined in base and derived class and not marked virtual in base class 916 | `e subclass 917 | 918 | `e invoking-superclass-constructor 919 | 920 | `e mark-class-underivable-or-method-unoverrideable 921 | sealed 922 | `e root-class 923 | System.Object 924 | `e root-class-methods 925 | Equals() 926 | 927 | Finalize() 928 | 929 | GetHashCode() 930 | 931 | GetType() 932 | 933 | MemberwiseClone() 934 | 935 | ReferenceEquals() 936 | 937 | ToString() 938 | `e get-type-class-of-object 939 | object o = new object(); 940 | 941 | System.Type t = o.GetType(); 942 | or 943 | 944 | System.type t = typeof(o); 945 | `e get-type-class-from-string 946 | using System; 947 | 948 | Type t = Type.GetType("object"); 949 | `e get-type-class-from-type-identifier 950 | System.Type t = typeof(object); 951 | `e class-name 952 | t.ToString(); 953 | `e get-methods 954 | using System.Reflection; 955 | 956 | System.Type t = typeof(object); 957 | 958 | MethodInfo[] a = t.GetMethods(); 959 | `e has-method 960 | null if method not found: 961 | 962 | MethodInfo m = t.GetMethod("ToString"); 963 | `e invoke-method-object 964 | m.Invoke(o); 965 | `e get-local-hostname-dns-lookup-reverse-dns-lookup 966 | 967 | `e http-get 968 | 969 | `e http-post 970 | 971 | `e absolute-url 972 | 973 | `e parse-url 974 | 975 | `e url-encode-decode 976 | 977 | `e base64-encode-decode 978 | 979 | `e test-class 980 | 981 | `e run-all-tests 982 | 983 | `e equality-assertion 984 | 985 | `e approximate-assertion 986 | 987 | `e exception-assertion 988 | 989 | `e setup 990 | 991 | `e teardown 992 | 993 | `e stronger-warnings 994 | 995 | `e suppress-warnings 996 | 997 | `e treat-warnings-as-errors 998 | 999 | `e run-debugger 1000 | 1001 | `e debugger-commands-help-list-source-re-load-executable-next-step-set-breakpoint-show-breakpoints-delete-breakpoint-continue-backtrace-up-stack-down-stack-print-run-quit 1002 | 1003 | `e benchmark-code 1004 | 1005 | `e profile-code 1006 | 1007 | `e memory-tool 1008 | 1009 | -------------------------------------------------------------------------------- /coffeescript.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | 1.7.1 3 | `e show-version 4 | `$[coffee --version] 5 | `e hello-world 6 | `e file-suffixes 7 | `e bytecode-compiler-and-interpreter 8 | `e native-compiler 9 | `e interpreter 10 | `$[coffee foo.coffee] 11 | `e repl 12 | `$[coffee] 13 | `e command-line-program 14 | `$[coffee -e 'var sys = require("sys"); 15 | sys.puts("hi world!");'] 16 | `e library-which-is-always-imported 17 | `e block-delimiters 18 | indentation 19 | `e statement-terminator 20 | `e top-level-statements 21 | `e source-code-encoding 22 | `e end-of-line-comment 23 | # comment 24 | `e multiple-line-comment 25 | ### 26 | comment 27 | another comment 28 | (will be preserved in generated JavaScript) 29 | ### 30 | `e local-variable 31 | x = 1 32 | `e uninitialized-local-variable 33 | `e regions-which-define-lexical-scope 34 | `e global-variable 35 | `e uninitialized-global-variable 36 | `e constant 37 | `e unit-type-and-value 38 | `e assignment 39 | x = 1 40 | `e parallel-assignment 41 | `e swap 42 | [x, y] = [y, x] 43 | `e compound-assignment-arithmetic-string-logical-bit 44 | `e increment-and-decrement 45 | `e address 46 | `e dereference 47 | `e type-size 48 | `e address-arithmetic 49 | `e unique-pointer 50 | `e reference-count-pointer 51 | `e weak-pointer 52 | `e allocate-heap 53 | `e uninitialized-heap 54 | `e free-heap 55 | `e null 56 | `e nullable-type 57 | `e null-test 58 | v? 59 | `e coalesce 60 | foo = `=undefined 61 | foo ? 4 62 | `e nullif 63 | `e conditional-expression 64 | `*if x > 0 `*then x `*else -x 65 | `e branch-type-mismatch 66 | `e expression-type-declaration 67 | `e let-in 68 | `e where 69 | `e boolean-type 70 | `e true-and-false 71 | `=true `=on `=yes 72 | `=false `=off `=no 73 | `e falsehoods 74 | `e logical-operators 75 | `+[&&] `*and `+[||] `*or `+[!] `*not 76 | `e relational-expression 77 | `e relational-operators 78 | `e compare-strings 79 | `e min-and-max 80 | `e three-value-comparison 81 | `e integer-type 82 | `e integer-literal 83 | `e unsigned-type 84 | `e float-type 85 | `e fixed-type 86 | `e arithmetic-expression 87 | `e arithmetic-operators 88 | `e integer-operators 89 | `e float-operators 90 | `e add-integer-and-float 91 | `e integer-division 92 | `e divmod 93 | `e integer-division-by-zero 94 | `e float-division 95 | `e float-division-by-zero 96 | `e power 97 | `e sqrt 98 | `e sqrt-1 99 | `e transcendental-functions 100 | `e transcendental-constants 101 | `e float-truncation 102 | `e absolute-value-and-signum 103 | `e arbitrary-length-integer 104 | `e arbitrary-length-integer-operators 105 | `e integer-overflow 106 | `e float-overflow 107 | `e float-limits-largest-finite-float-smallest-positive-float 108 | `e rational-type 109 | `e rational-construction 110 | `e rational-decomposition 111 | `e complex-type 112 | `e complex-constants 113 | `e complex-construction 114 | `e complex-decomposition-real-and-imaginary-component-argument-absolute-value-conjugate 115 | `e complex-operators 116 | `e random-number-uniform-integer-uniform-float-normal-float 117 | `e random-seed 118 | `e bit-operators 119 | `e binary-octal-and-hex-literals 120 | `e radix-convert-integer-to-and-from-string-with-radix 121 | `e string-type 122 | `e string-literal 123 | `e newline-in-literal 124 | `e literal-escapes 125 | `e allocate-string 126 | `e are-strings-mutable 127 | `e custom-delimiters 128 | `e here-document 129 | `e variable-interpolation 130 | count = 3 131 | item = ball 132 | alert "`%[#{count}] `%[#{item}]s" `c[double-quoted strings only] 133 | `e expression-interpolation 134 | `e format 135 | `e compare-strings 136 | `e are-strings-mutable 137 | `e copy-string 138 | `e concatenate-strings 139 | `e replicate-string 140 | `e translate-case 141 | `e capitalize 142 | `e trim 143 | `e pad 144 | `e number-to-string 145 | `e string-to-number 146 | `e join 147 | `e split 148 | `e split-in-two 149 | `e split-and-keep-delimiters 150 | `e serialize 151 | `e string-length 152 | `e index-of-substring 153 | `e extract-substring 154 | `e extract-character 155 | `e character-type 156 | `e character-literal 157 | `e test-character 158 | `e chr-and-ord 159 | `e to-array-of-characters 160 | `e translate-characters 161 | `e delete-characters 162 | `e squeeze-characters 163 | `e regex-type 164 | `e literal-custom-delimited-literal 165 | `e character-class-abbreviations 166 | `e anchors 167 | `e lookahead-positive-negative 168 | `e match-test 169 | `e case-insensitive-match-test 170 | `e modifiers 171 | `e substitution 172 | `e match-prematch-postmatch 173 | `e group-capture 174 | `e named-group-capture 175 | `e scan 176 | `e backreference-in-match-and-substitution 177 | `e recursive-regex 178 | `e date-time-type 179 | `e current-date-time 180 | `e to-unix-epoch-from-unix-epoch 181 | `e current-unix-epoch 182 | `e date-and-time-to-string 183 | `e format-date 184 | `e strftime 185 | `e default-format-example 186 | `e strptime 187 | `e parse-date 188 | `e parse-date-w-o-format 189 | `e date-subtraction 190 | `e add-duration 191 | `e date-parts 192 | `e time-parts 193 | `e build-date-time-from-parts 194 | `e local-timezone 195 | `e arbitrary-timezone 196 | `e timezone-name-offset-from-utc-is-daylight-savings 197 | `e microseconds 198 | `e sleep 199 | `e timeout 200 | `e declare-on-stack 201 | `e declare-on-heap 202 | `e free-heap 203 | `e array-initialization-list 204 | `e array-size 205 | `e array-lookup 206 | `e array-update 207 | `e array-out-of-bounds 208 | `e array-copy 209 | `e as-function-argument 210 | `e array-iterate 211 | `e array-sort 212 | `e list-name 213 | `e list-declare 214 | `e head-and-tail-of-empty-list 215 | `e list-literal 216 | `e quote-words 217 | `e list-size 218 | `e capacity-get-increase 219 | `e empty-list 220 | `e empty-test 221 | `e empty-test-and-clear 222 | `e head 223 | `e list-lookup 224 | `e list-update 225 | `e list-out-of-bounds 226 | `e index-of-element 227 | `e cons 228 | `e slice 229 | `e take 230 | `e drop 231 | `e last-and-butlast 232 | `e manipulate-back 233 | `e manipulate-front 234 | `e concatenate 235 | `e concatenate-two-lists-list-of-lists 236 | `e list-replicate 237 | `e list-copy 238 | `e array-as-function-arguments 239 | `e arrays-as-function-arguments 240 | `e iterate-over-elements 241 | `e iterate-over-indices-and-elements 242 | `e iterate-over-range 243 | `e instantiate-range-as-list 244 | `e reverse 245 | `e sort 246 | `e dedupe 247 | `e membership 248 | `e map 249 | `e filter 250 | `e fold-from-left 251 | `e fold-from-right 252 | `e universal-test 253 | `e existential-test 254 | `e intersection 255 | `e union 256 | `e relative-complement-symmetric-difference 257 | `e min-and-max-element 258 | `e shuffle-and-sample 259 | `e zip 260 | `e zip-lists 261 | `e declare-pair 262 | `e lookup-pair-elements 263 | `e update-pair-elements 264 | `e pair-element-access 265 | `e tuple 266 | `e declare-tuple 267 | `e tuple-element-access 268 | `e lookup-tuple-elements 269 | `e update-tuple-elements 270 | `e tuple-size 271 | `e create-references-for-tuple-elements 272 | `e map-declaration 273 | `e map-access 274 | `e map-size 275 | `e map-remove-element 276 | `e map-element-not-found-result 277 | `e map-iterate 278 | `e map-literal 279 | `e map-lookup 280 | `e map-out-of-bounds 281 | `e is-key-present 282 | `e delete-entry 283 | `e from-array-of-pairs-from-even-length-array 284 | `e merge 285 | `e invert 286 | `e iteration 287 | `e keys-and-values-as-arrays 288 | `e sort-by-values 289 | `e default-value-computed-value 290 | `e declare-function 291 | `e define-function 292 | `e define-function-with-block-body 293 | `e invoke-function 294 | add(1, 2) 295 | add 1, 2 296 | `e apply-function-to-array 297 | `e define-static-class-method 298 | `e invoke-static-class-method 299 | `e overload-function 300 | `e missing-argument-behavior 301 | `e extra-arguments 302 | `e default-argument 303 | myLog = (x, base = 10) -> Math.log(x) / Math.log(base) 304 | `e variable-number-of-arguments 305 | `e named-parameters 306 | `e named-parameter-default-value 307 | `e pass-by-value 308 | `e pass-by-reference 309 | `e pass-by-address 310 | `e pass-number-or-string-by-reference 311 | `e pass-array-or-dictionary-by-reference 312 | `e return-value 313 | `e no-return-value 314 | `e multiple-return-values 315 | `e piecewise-defined-function 316 | `e recursive-function 317 | `e mutually-recursive-functions 318 | `e lambda 319 | square = (x) `+[->] x * x 320 | `e lambda-invocation 321 | `e closure 322 | `e function-as-value 323 | `e function-with-private-state 324 | `e generator 325 | `e decorator 326 | `e operator-as-function 327 | `e overload-operator 328 | `e default-scope 329 | `e default-value 330 | `e nested-function-visibility 331 | `e infix-operator-in-prefix-position 332 | `e function-in-infix-position 333 | `e currying 334 | `e composition 335 | `e function-composition-operator 336 | `e lazy-evaluation 337 | `e strict-evaluation 338 | `e if 339 | `*if 0 == n 340 | alert "no hits" 341 | `*else `*if 1 == n 342 | alert "1 hit" 343 | `*else 344 | alert n + "hits" 345 | `e dangling-else 346 | `e sequencing 347 | `e switch 348 | `*switch n 349 | `*when 0 `*then "no hits" 350 | `*when 1 `*then "one hit" 351 | `*else "#{n} hits" 352 | `e while 353 | `*while i < 100 354 | i += 1 355 | `c[when used as an expression, returns array containing result of each iteration] 356 | `c[alternate] 357 | i += 1 `*while i < 100 358 | `e for 359 | `*for i `*in [0...10] 360 | alert i 361 | 362 | name `*for name `*of window `c[iterate over properties] 363 | `e for-in-reverse 364 | `e c-style-for 365 | `e break 366 | `e break-out-of-nested-loops 367 | `e continue 368 | `e goto 369 | `e break-continue-redo 370 | `e control-structure-keywords 371 | `e what-do-does 372 | immediately invokes a function, forwarding arguments (useful for forcing closure) 373 | `e statement-modifiers 374 | `e generator 375 | `e list-iteration 376 | `e base-exception 377 | `e type-of-exceptions 378 | `e predefined-exceptions 379 | `e standard-exceptions 380 | `e define-exception 381 | `e user-defined-exception 382 | `e raise-exception 383 | `e re-raise-exception 384 | `e handle-exception 385 | `e catch-exception 386 | `e catch-exception-by-type 387 | `e catch-all-handler 388 | `e global-variable-for-last-exception 389 | `e finally 390 | `e multiple-handlers 391 | `e uncaught-exception-behavior 392 | `e error-message 393 | `e system-call-errno 394 | `e exception-specification 395 | `e assert 396 | `e raise-error 397 | `e handle-error 398 | `e start-thread 399 | `e terminate-current-thread 400 | `e terminate-other-thread 401 | `e list-threads 402 | `e wait-on-thread 403 | `e lock 404 | `e create-message-queue 405 | `e send-message 406 | `e receive-message 407 | `e standard-file-handles 408 | `e read-line-from-stdin 409 | `e write-line-to-stdout 410 | `e printf 411 | `e open-file 412 | `e open-file-for-reading 413 | `e open-file-for-writing 414 | `e open-file-for-appending 415 | `e set-file-handle-encoding 416 | `e read-line 417 | `e chomp 418 | `e read-file 419 | `e read-from-file 420 | `e iterate-over-file-by-line 421 | `e read-file-into-string 422 | `e read-file-into-array-of-strings 423 | `e write-to-file 424 | `e write-string 425 | `e write-line 426 | `e flush-file-handle 427 | `e close-file 428 | `e close-file-implicitly 429 | `e end-of-file-test 430 | `e end-of-file-behavior 431 | `e i-o-error 432 | `e i-o-errors 433 | `e encoding-error 434 | `e get-and-set-file-handle-position 435 | `e temporary-file 436 | `e in-memory-file 437 | `e file-exists-test-regular-test 438 | `e file-size 439 | `e is-file-readable-writable-executable 440 | `e set-file-permissions 441 | `e copy-file-remove-file-rename-file 442 | `e create-symlink-symlink-test-readlink 443 | `e generate-unused-file-name 444 | `e last-modification-time 445 | `e csv 446 | `e parse-csv 447 | `e generate-csv 448 | `e generate-xml 449 | `e parse-html 450 | `e json 451 | `e json-generate-parse 452 | `e build-xml 453 | `e parse-xml 454 | `e parse-xml-all-nodes-matching-xpath-query-first-node-matching-xpath-query 455 | `e parse-html 456 | `e working-directory 457 | `e build-pathname 458 | `e dirname-and-basename 459 | `e absolute-pathname 460 | `e absolute-pathname-and-tilde-expansion 461 | `e iterate-over-directory-by-file 462 | `e glob-paths 463 | `e make-directory 464 | `e recursive-copy 465 | `e remove-empty-directory 466 | `e remove-directory-and-contents 467 | `e directory-test 468 | `e generate-unused-directory 469 | `e generate-unused-directory-name 470 | `e system-temporary-file-directory 471 | `e exit 472 | `e program-name 473 | `e command-line-arguments 474 | `e command-line-arguments-and-script-name 475 | `e signature-of-main 476 | `e first-argument 477 | `e getopt 478 | `e get-and-set-environment-variable 479 | `e get-pid-parent-pid 480 | `e get-user-id-and-name 481 | `e environment-variable 482 | `e iterate-through-environment-variables 483 | `e exit 484 | `e set-signal-handler 485 | `e executable-test 486 | `e external-command 487 | `e escaped-external-command 488 | `e backticks 489 | `e command-line-options-boolean-option-option-with-argument-usage 490 | `e library 491 | `e load-library 492 | `e load-library-in-subdirectory 493 | `e hot-patch 494 | `e load-error 495 | `e standard-library-name 496 | `e main-routine-in-library 497 | `e library-path 498 | `e library-path-environment-variable 499 | `e library-path-command-line-option 500 | `e declare-namespace 501 | `e simple-global-identifiers 502 | `e multiple-label-identifiers 503 | `e label-separator 504 | `e root-namespace-definition 505 | `e declare-namespace 506 | `e child-namespace-declaration 507 | `e namespace-alias 508 | `e unqualified-import-of-namespace 509 | `e unqualified-import-of-all-subnamespaces 510 | `e unqualified-import-of-definitions 511 | `e list-installed-packages-install-a-package 512 | `e package-specification-format 513 | `e namespace-example 514 | `e namespaces 515 | `e file-name-restrictions 516 | `e namespace 517 | `e namespace-creation 518 | `e namespace-alias 519 | `e namespace-separator 520 | `e subnamespace 521 | `e namespace-separator 522 | `e multiple-namespaces-per-file 523 | `e namespaces-map-to-directories 524 | `e import-namespace 525 | `e import-library 526 | `e import-part-of-namespace 527 | `e import-symbol 528 | `e import-static-symbol 529 | `e import-position 530 | `e using-a-symbol-that-hasn-t-been-imported 531 | `e application-environment 532 | `e multiple-installations 533 | `e package-manager 534 | `e package-manager-setup 535 | `e list-installed-packaged-install-a-package 536 | `e package-manager-search-install-list-installed 537 | `e library-path 538 | `e library-path-environment-variable 539 | `e compile-app-using-package 540 | `e type-synonym 541 | `e sum-type 542 | `e tuple-product-type-with-one-field 543 | `e tuple-product-type-with-two-fields 544 | `e enum 545 | `e struct-definition 546 | `e struct-declaration 547 | `e struct-initialization 548 | `e struct-member-assignment 549 | `e struct-member-access 550 | `e record-product-type 551 | `e record-product-type-literal 552 | `e recursive-type 553 | `e pattern-match-sum-type 554 | `e pattern-match-product-type 555 | `e pattern-match-guard 556 | `e pattern-match-catchall 557 | `e generic-type 558 | `e define-generic-type 559 | `e instantiate-generic-type 560 | `e generic-function 561 | `e generic-array 562 | `e value-parameter 563 | `e template-parameter 564 | `e template-specialization 565 | `e multiple-type-parameters 566 | `e generic-type-parameters 567 | `e template-parameters 568 | `e variadic-template 569 | `e semantics-of 570 | `e define-class 571 | `e class-definition-location 572 | `e constructor 573 | `e create-object 574 | `e create-blank-object 575 | `e instance-variable-visibility 576 | `e get-and-set-instance-variable 577 | `e set-attribute 578 | `e get-attribute 579 | `e destructor 580 | `e destroy-object 581 | `e define-method 582 | `e invoke-method 583 | `e define-class-method 584 | `e invoke-class-method 585 | `e define-class-variable 586 | `e get-and-set-class-variable 587 | `e handle-undefined-method-invocation 588 | `e clone-object 589 | `e object-literal 590 | `e name-of-receiver 591 | `e access-control 592 | `e anonymous-class 593 | `e alias-method 594 | `e destructor 595 | `e subclass 596 | `e dynamic-dispatch 597 | `e static-dispatch 598 | `e mixin 599 | `e overload-function 600 | `e overload-operator 601 | `e subclass 602 | `e inheritance 603 | `e invoking-superclass-constructor 604 | `e mark-class-underivable-or-method-unoverrideable 605 | `e root-class 606 | `e root-class-methods 607 | `e get-type-class-of-object 608 | `e get-type-class-from-string 609 | `e get-type-class-from-type-identifier 610 | `e inspect-class 611 | `e inspect-class-hierarchy 612 | `e object-id 613 | `e inspect-type 614 | `e basic-types 615 | `e class-name 616 | `e get-methods 617 | `e has-method 618 | `e invoke-method-object 619 | `e inspect-type 620 | `e has-method 621 | `e message-passing 622 | `e eval 623 | `e inspect-methods 624 | `e inspect-attributes 625 | `e list-obj-object-methods 626 | `e list-object-attributes 627 | `e list-loaded-libraries 628 | `e list-loaded-namespaces 629 | `e inspect-namespace 630 | `e pretty-print 631 | `e source-line-number-and-file-name 632 | `e command-line-documentation 633 | `e get-local-hostname-dns-lookup-reverse-dns-lookup 634 | `e http-get 635 | `e http-post 636 | `e serve-working-directory 637 | `e absolute-url 638 | `e absolute-url-from-base-and-relative-url 639 | `e parse-url 640 | `e url-encode-decode 641 | `e base64-encode-decode 642 | `e test-class 643 | `e run-tests-run-test-method 644 | `e run-all-tests 645 | `e equality-assertion 646 | `e approximate-assertion 647 | `e regex-assertion 648 | `e exception-assertion 649 | `e mock-method 650 | `e setup 651 | `e teardown 652 | `e check-syntax 653 | `e stronger-warnings 654 | `e stronger-warnings 655 | `e suppress-warnings 656 | `e treat-warnings-as-errors 657 | `e run-debugger 658 | `e debugger-commands-help-list-source-re-load-executable-next-step-set-breakpoint-show-breakpoints-delete-breakpoint-continue-backtrace-up-stack-down-stack-print-run-quit 659 | `e debugger-commands 660 | `e benchmark-code 661 | `e profile-code 662 | `e memory-tool 663 | `e lint 664 | `e source-cleanup 665 | `e invoke-repl 666 | `e repl-limitations 667 | `e repl-last-value 668 | `e help 669 | `e quit 670 | `e inspect-type 671 | `e inspect-namespace 672 | `e load-source-file 673 | `e load-package 674 | `e search-path 675 | `e set-search-path-on-command-line 676 | `e java-version 677 | `e java-repl 678 | `e java-interpreter 679 | `e java-compiler 680 | `e java-prologue 681 | `e java-new 682 | `e java-method 683 | `e java-import 684 | `e non-bundled-java-libraries 685 | `e java-shadowing-avoidance 686 | `e convert-native-array-to-java-array 687 | `e are-java-classes-subclassable 688 | `e are-java-class-open 689 | -------------------------------------------------------------------------------- /d.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | D 2.066.0 3 | `e show-version 4 | `$[dmd -v] 5 | `e implicit-prologue 6 | `e hello-world 7 | `$[cat hello.d] 8 | `*import std.stdio; 9 | 10 | `*void main() { 11 | writeln(`=["Hello world!"]); 12 | } 13 | `e file-suffixes 14 | foo.d 15 | `e interpreter 16 | `c[sort of] 17 | `$[dmd -run foo.d] 18 | `e block-delimiters 19 | { } 20 | `e statement-terminator 21 | ; 22 | `e top-level-statements 23 | `e end-of-line-comment 24 | // comment 25 | `e multiple-line-comment 26 | /* comment 27 | another comment */ 28 | `e local-variable 29 | `*int i; 30 | `*int j = 3; 31 | `e uninitialized-local-variable 32 | `e global-variable 33 | `e uninitialized-global-variable 34 | `e constant 35 | `c[compile-time/manifest constant:] 36 | `*enum `*int i = 7; 37 | `c[must be constant in the entire program:] 38 | `*immutable `*int j = 7; 39 | `c[not changeable through this pointer:] 40 | `*const `*int k = 7; 41 | `e assignment 42 | `*int n; 43 | 44 | n = 3; 45 | `e compound-assignment-arithmetic-string-logical-bit 46 | `+[+= -= *= /= %= ^^=] 47 | `+[<<= >>= &= ^= |=] 48 | `e increment-and-decrement 49 | `*int n = 1; 50 | `*int one = n++; 51 | `*int three = ++n; 52 | `*int two = --n; 53 | `e address 54 | `e dereference 55 | `e type-size 56 | (`*int*).sizeof 57 | `e address-arithmetic 58 | 59 | `e unique-pointer 60 | 61 | `e reference-count-pointer 62 | 63 | `e weak-pointer 64 | 65 | `e allocate-heap 66 | `e uninitialized-heap 67 | `e free-heap 68 | `e null 69 | `*null 70 | `e nullable-type 71 | `*import std.typecons; 72 | Nullable!T 73 | `c[usage:] 74 | Nullable!`*int a; 75 | a = 5; 76 | a.nullify(); `c[set to null] 77 | `e null test 78 | v `*is `*null 79 | `c[Nullable!T:] 80 | v.isNull 81 | `e coalesce 82 | `e conditional-expression 83 | x > 0 ? x : -x 84 | `e boolean-type 85 | `*bool 86 | `e true-and-false 87 | `=true `=false 88 | `e falsehoods 89 | `=false `=0 `=[0.0] `.NULL 90 | `e logical-operators 91 | `+[&& || !] 92 | `e relational-operators 93 | `+[== != < > <= >=] 94 | `+[!<>= <> <>= !<= !< !>= !> !<>] `c[handles NaN differently] 95 | `*is `+!`*is 96 | `e integer-type 97 | `*byte n1; `c[1 byte] 98 | `*short n2; `c[2 bytes] 99 | `*int n3; `c[4 bytes] 100 | `*long n4; `c[8 bytes] 101 | `e unsigned-type 102 | `*ubyte n1; `c[1 byte] 103 | `*ushort n2; `c[2 bytes] 104 | `*uint n3; `c[4 bytes] 105 | `*ulong n4; `c[8 bytes] 106 | `e float-type 107 | `*float x1; `c[4 bytes] 108 | `*double x2; `c[8 bytes] 109 | `*real x3; `c[largest in hardware] 110 | `e fixed-type 111 | `c[none] 112 | `e arithmetic-operators 113 | `+[+ - * / % ^^] 114 | `e integer-division 115 | `c[evaluates to 2:] 116 | 7 / 3 117 | `e integer-division-by-zero 118 | `e float-division 119 | `e float-division-by-zero 120 | positive dividend: `*double.infinity 121 | zero dividend: `*double.nan 122 | negative dividend: -`*double.infinity 123 | `e power 124 | `=2 `+[^^] `=20 125 | `=[2.0] `+[^^] `=[32.0] 126 | `e sqrt 127 | `e sqrt-1 128 | nan 129 | `e transcendental-functions 130 | `*import std.math; 131 | 132 | exp log log2 log10 133 | sin cos tan 134 | asin acos atan 135 | atan2 136 | `e transcendental-constants 137 | `*import std.math; 138 | 139 | E PI 140 | `e float-truncation 141 | `*double x = 3.7; 142 | 143 | `*long trnc = `*cast(`*long)(x); 144 | `e absolute-value-and-signum 145 | `e integer-overflow 146 | modular arithmetic, see http://dlang.org/expression.html#AddExpression 147 | `e float-overflow 148 | IEEE 754 149 | `e float-limits-largest-finite-float-smallest-positive-float 150 | `*float.max 151 | `*float.min_normal 152 | `*double.max 153 | `*double.min_normal 154 | `*real.max 155 | `*real.min_normal 156 | `e complex-construction 157 | `c[built-in (deprecated]) 158 | `*cfloat c = 1 + 3.14 * 1.0i; 159 | `*cdouble z = 1 + 3.14 * 1.0i; 160 | 161 | `c[modern] 162 | `*import std.complex; 163 | 164 | `*auto c = complex(2.0); 165 | `*auto z = complex(1, 3.14L); 166 | `e complex-decomposition 167 | `c[built-in (deprecated]) 168 | 169 | `c[modern] 170 | z.re 171 | z.im 172 | `e random-number-uniform-integer-uniform-float-normal-float 173 | `e random-seed 174 | `e bit-operators 175 | << >> & | ^ ~ 176 | `e binary-octal-and-hex-literals 177 | `=[0b0101010] 178 | `=[052] 179 | `=[0x2a] 180 | `e radix-convert-integer-to-and-from-string-with-radix 181 | 182 | `e string-type 183 | `*char[] s = "lorem ipsum"; 184 | `e string-literal 185 | `c[string, aka immutable char[]:] 186 | `=["don't say `%[\"]no`%[\"]"] 187 | `e newline-in-literal 188 | `e literal-escapes 189 | `%[\a \b \f \n \r \t \v] 190 | `%[\\ \" \'] 191 | `%[\xhh \o \oo \ooo] 192 | `e allocate-string 193 | `.string s = "hello"; 194 | `e are-strings-mutable 195 | `c[no, but char[]s are:] 196 | `*char[] s = `=["bar"].dup; 197 | 198 | s[2] = `=['z']; 199 | `e copy-string 200 | `c[not necessary for strings since they're immutable, but] 201 | `*const `*char[] s = `=["bar"]; 202 | 203 | `*char[] s2 = s.dup; 204 | `*char[] s3 = s; 205 | 206 | `c[s contains "baz"; s2 and s3 contain "bar":] 207 | s[2] = `=['z']; 208 | `e format 209 | `e compare-strings 210 | `+[== != < > <= >=] 211 | `e concatenate-strings 212 | `c[same as arrays:] 213 | `.string s = "hello"; 214 | `.string s2 = s ~ " world"; 215 | 216 | s ~= " world"; 217 | `e replicate 218 | `e translate-case 219 | `e trim 220 | `e pad 221 | `e number-to-string 222 | `*import std.conv; 223 | to!`.string(14) 224 | `e string-to-number 225 | `*import std.conv; 226 | to!`.int(14) 227 | `e join 228 | `e split 229 | `e serialize 230 | `e string-length 231 | `*const `*char[] s = "hello"; 232 | `*int len = s.length; 233 | `e index-of-substring 234 | `e extract-substring 235 | `e character-type 236 | `*char 237 | `*wchar 238 | `*dchar 239 | `e character-literal 240 | `*char n = 'X'; 241 | `e test-character 242 | `e regex-type 243 | `e character-class-abbreviations 244 | . \d \D \s \S \w \W 245 | `e anchors 246 | ^ $ \b \B 247 | `e lookahead-positive-negative 248 | `e match-test 249 | `e case-insensitive-match-test 250 | 251 | `e modifiers 252 | 253 | `e substitution 254 | 255 | `e match-prematch-postmatch 256 | 257 | `e group-capture 258 | 259 | `e date-time-type 260 | 261 | `e current-date-time 262 | 263 | `e to-unix-epoch-from-unix-epoch 264 | 265 | `e date-and-time-to-string 266 | 267 | `e format-date 268 | 269 | `e parse-date 270 | 271 | `e date-subtraction 272 | 273 | `e add-duration 274 | 275 | `e date-parts 276 | 277 | `e time-parts 278 | 279 | `e declare-on-stack 280 | `*int[10] a; 281 | `e declare-on-heap 282 | `*int[] a; 283 | a.length = 10; 284 | `e free-heap 285 | `e array-initialization-list 286 | `*int a[3] = [1, 2, 3]; 287 | `e array-size 288 | `*int a[10]; 289 | a.length; 290 | `e array-lookup 291 | `*int first = a[0]; 292 | `e array-update 293 | a[0] = 7; 294 | `e array-out-of-bounds 295 | RangeError if detected 296 | `e copy 297 | `e as-function-argument 298 | `e array-iterate 299 | int a[] = [ 3, 2, 4, 1 ]; 300 | `*foreach (i, e; a) { 301 | writeln("value at ", i, " is ", e); 302 | } 303 | `e array-sort 304 | `*import std.algorithm; 305 | 306 | `*bool comp(`*int a, `*int b) @safe `*pure `*nothrow { 307 | `*return a < b ? -1 : (a == b ? 0 : 1); 308 | } 309 | 310 | `*int[] arr = [3, 2, 1, 4]; 311 | sort!("a > b")(arr); `c[first pair of parens optional] 312 | sort!(comp)(arr); `c[first pair of parens optional] 313 | `e list-name 314 | T[] 315 | `e list-declare 316 | `*int[] a; 317 | `e list-literal 318 | [1, 2, 3] 319 | `e list-size 320 | a.length 321 | `e capacity-get-increase 322 | a.capacity 323 | a.capacity = 10; 324 | `e empty-test-and-clear 325 | `*bool isEmpty = a.empty; 326 | 327 | a.length = `=0; 328 | `e list-lookup 329 | a[0] 330 | `e list-update 331 | a[2] = 4; 332 | `e out-of-bounds 333 | `e index-of-element 334 | `e slice 335 | `e drop 336 | `e manipulate-back 337 | `e manipulate-front 338 | `e concatenate 339 | `*int[] a = [1, 2, 3]; 340 | `*int[] b = [4, 5, 6]; 341 | `*int[] c = a1 ~ a2; 342 | a1 ~= a2; 343 | `e list-replicate 344 | `e copy 345 | `e array-as-function-argument 346 | `e iterate-over-elements 347 | `*int sum = 0; 348 | `*int[3] a = [1, 2, 3]; 349 | 350 | `*foreach (n; a) { 351 | sum += n; 352 | } 353 | `e iterate-over-indices-and-elements 354 | `*int[3] a = [6, 7, 8]; 355 | `*foreach (i, n; a) { 356 | writeln("value at ", i, " is ", n); 357 | } 358 | `e iterate-over-range 359 | `*foreach (i; 1..1000001) { 360 | `c[code] 361 | } 362 | `e instantiate-range-as-list 363 | `*import std.range; 364 | `*auto a = iota(1, 11).array; `c[1, 2, ..., 10] 365 | iota(11) `c[0, 1, 2, ..., 10] 366 | iota(1, 11, 2) `c[1, 3, 5, 7, 9] 367 | `e reverse 368 | `e sort 369 | `e dedupe 370 | `e membership 371 | `e intersection 372 | `e union 373 | `e relative-complement-symmetric-difference 374 | `e map 375 | `*import std.algorithm; 376 | map!(x => x * x)([1, 2, 3]) `c[same as] [1, 2, 3].map!(x => x * x) 377 | map!`=["a * a"]([1, 2, 3]) `c[same as] [1, 2, 3].map!`=["a * a"] 378 | `c[these are lazy ranges; call .array to get an array] 379 | `e filter 380 | `*import std.algorithm; 381 | filter!(x => x > 1)([1, 2, 3]) `c[same as] [1, 2, 3].filter!(x => x > 1) 382 | filter!`=["a > 1"]([1, 2, 3]) `c[same as] [1, 2, 3].filter!`=["a > 1"] 383 | `e min-and-max-element 384 | 385 | `e shuffle-and-sample 386 | 387 | `e zip 388 | 389 | `e declare-pair 390 | `*import std.typecons; 391 | Tuple!(string, int) p1; 392 | Tuple!(string, int) p2 = tuple(`=["foo"], `=7); 393 | `e lookup-pair-elements 394 | `*auto p = tuple("foo", 7); 395 | 396 | p[0] 397 | p[1] 398 | `e update-pair-elements 399 | p[0] = `=["bar"]; 400 | p[1] = `=8; 401 | `e declare-tuple 402 | Tuple!(string, `*int, `*float) tup1; 403 | Tuple!(string, `*int, `*float) tup2 = tuple(`=["foo"], `=1, `=[3.7]); 404 | 405 | `*auto tup3 = tuple("foo", 1, 3.7); 406 | `e lookup-tuple-elements 407 | tup3[0] 408 | tup3[1] 409 | tup3[2] 410 | `e update-tuple-elements 411 | tup3[0] = "bar"; 412 | `e tuple-size 413 | 414 | `e create-references-for-tuple-elements 415 | 416 | `e map-declaration 417 | `*int[`*string] m; 418 | `e map-access 419 | m[`=["hello"]] = 5; 420 | writeln(m[`=["hello"]]); 421 | `e map-size 422 | m.length 423 | `e map-remove-element 424 | `e map-element-not-found-result 425 | `e map-iterate 426 | `*foreach (k, v; m) { 427 | writeln(k, " ", v); 428 | } 429 | `e declare-function 430 | `e define-function 431 | `*int add(`*int m, `*int n) { 432 | `*return m + n; 433 | } 434 | `e invoke-function 435 | `*int sum = add(3, 7); 436 | `e define-static-class-method 437 | `e default-argument 438 | `e variable-number-of-arguments 439 | 440 | `e named-parameters 441 | `e pass-by-value 442 | `*int add1(`*int n) { 443 | `*return ++n; 444 | } 445 | 446 | `*int i = 7; 447 | `*int i2 = add1(i); 448 | `e pass-by-reference 449 | `*int add1(`*ref `*int n) { 450 | `*return ++n; 451 | } 452 | 453 | `*int i = 7; 454 | `*int i2 = add1(i); 455 | `e pass-by-address 456 | `*int add1(`*int* n) { 457 | `*return ++*n; 458 | } 459 | 460 | `*int i = 7; 461 | `*int i2 = add1(&i); 462 | `e return-value 463 | `e no-return-value 464 | `e recursive-function 465 | `*int factorial(`*int n) { 466 | `*if (n <= 1) { 467 | `*return 1; 468 | } 469 | `*return n * factorial(n - 1); 470 | } 471 | `e lambda 472 | `e invoke-anonymous-function 473 | `e closure 474 | `e function-with-private-state 475 | `e function-as-value 476 | `e overload-operator 477 | `*ref Rational opBinary(`*string op)(`*in Rational o) 478 | `*if (op == "+") { `c[compile-time test] 479 | `*return Rational(`*this.num * o.denom + o.num * `*this.denom, `*this.denom * o.denom); 480 | } 481 | `e if 482 | `*int signum; 483 | `*if (n > 0) { 484 | signum = 1; 485 | } `*else `*if (n == 0) { 486 | signum = 0; 487 | } `*else { 488 | signum = -1; 489 | } 490 | `e dangling-else 491 | `e switch 492 | `*const `*int INVALID_BINARY_DIGIT = -`=1; 493 | `*int bin_digit; 494 | 495 | `*switch(n) { 496 | `*case `=0, `=1: 497 | bin_digit = n; 498 | `*break; 499 | `*default: 500 | bin_digit = INVALID_BINARY_DIGIT; 501 | `*break; 502 | } 503 | `e while 504 | `*int i = 1, fact = 1, n = 10; 505 | 506 | `*while (i < n) { 507 | fact *= i; 508 | ++i; 509 | } 510 | `e for 511 | `*int fact; 512 | `*for (i; 1 .. 11) { `c[half-open] 513 | fact *= i; 514 | } 515 | `e break 516 | `e break-out-of-nested-loops 517 | `e continue 518 | `e goto 519 | `e base-exception 520 | `e predefined-exceptions 521 | `e handle-exception 522 | `e define-exception 523 | `e re-raise-exception 524 | `e catch-all-handler 525 | `e multiple-handlers 526 | `e uncaught-exception-behavior 527 | `e error-message 528 | `e system-call-errno 529 | `e finally 530 | `e exception-specification 531 | `e start-thread 532 | `e terminate-current-thread 533 | `e terminate-other-thread 534 | `e list-threads 535 | `e wait-on-thread 536 | `e lock 537 | `e create-message-queue 538 | `e send-message 539 | `e receive-message 540 | `e standard-file-handles 541 | stdin 542 | stderr 543 | stdout 544 | `e read-line-from-stdin 545 | `*string line = readln(); 546 | `e write-line-to-stdout 547 | writeln("Hello, world!"); 548 | `e printf 549 | writef("count: `%[%d\n]", `=7); 550 | writefln("count: %d", `=7); 551 | `e read-from-file 552 | `e write-to-file 553 | `e file-exists-test-regular-test 554 | `e file-size 555 | `e is-file-readable-writable-executable 556 | `e set-file-permissions 557 | `e copy-file-remove-file-rename-file 558 | `e csv 559 | `e json 560 | `e build-xml 561 | `e parse-xml 562 | `e parse-html 563 | `e build-pathname 564 | `e dirname-and-basename 565 | `e absolute-pathname 566 | `e iterate-over-directory-by-file 567 | `e glob-paths 568 | `e make-directory 569 | `e recursive-copy 570 | `e remove-empty-directory 571 | `e remove-directory-and-contents 572 | `e directory-test 573 | `e generate-unused-directory-name 574 | `e system-temporary-file-directory 575 | `e signature-of-main 576 | `e first-argument 577 | `e environment-variable 578 | `e iterate-through-environment-variables 579 | `e standard-library-name 580 | `e declare-namespace 581 | `e multiple-namespaces-per-file 582 | `e namespaces-map-to-directories 583 | `e import-namespace 584 | `e import-part-of-namespace 585 | `e import-symbol 586 | `e import-static-symbol 587 | `e import-position 588 | `e using-a-symbol-that-hasn-t-been-imported 589 | `e application-environment 590 | `e multiple-installations 591 | `e package-manager 592 | `e type-synonym 593 | `*alias customer_id = `*int; 594 | customer_id cid = `=3; 595 | `e enum 596 | `*enum DayOfWeek { Mon, Tue, Wed, Thu, Fri, Sat, Sun} 597 | DayOfWeek d = Tue; 598 | `e struct-definition 599 | `*class MedalCount { 600 | `*string country; 601 | `*int gold; 602 | `*int silver; 603 | `*int bronze; 604 | } 605 | `e struct-declaration 606 | MedalCount spain; 607 | `e struct-initialization 608 | MedalCount spain = MedalCount("Spain", 3, 7, 4); 609 | `e struct-member-assignment 610 | spain.country = "Spain"; 611 | spain.gold = 3; 612 | spain.silver = 7; 613 | spain.bronze = 4; 614 | `e struct-member-access 615 | `*int spain_total = spain.gold + spain.silver + spain.bronze; 616 | `e define-generic-type 617 | `e instantiate-generic-type 618 | `e generic-function 619 | `e generic-array 620 | `e value-parameter 621 | `e template-parameter 622 | `e template-specialization 623 | `e multiple-type-parameters 624 | `e generic-type-parameters 625 | `e template-parameters 626 | `e variadic-template 627 | `e semantics-of 628 | value comparison 629 | `e define-class 630 | `e class-definition-location 631 | `e constructor 632 | `e create-object 633 | `e destructor 634 | `e destroy-object 635 | `e define-method 636 | `e invoke-method 637 | `e define-class-method 638 | `e invoke-class-method 639 | `e name-of-receiver 640 | `e access-control 641 | `e anonymous-class 642 | `e dynamic-dispatch 643 | `e static-dispatch 644 | `e subclass 645 | `e invoking-superclass-constructor 646 | `e mark-class-underivable-or-method-unoverrideable 647 | `e root-class 648 | `e root-class-methods 649 | `e get-type-class-of-object 650 | `e get-type-class-from-string 651 | `e get-type-class-from-type-identifier 652 | `e class-name 653 | `e get-methods 654 | `e has-method 655 | `e invoke-method-object 656 | `e get-local-hostname-dns-lookup-reverse-dns-lookup 657 | `e http-get 658 | `e http-post 659 | `e absolute-url 660 | `e parse-url 661 | `e url-encode-decode 662 | `e base64-encode-decode 663 | `e test-class 664 | `e run-all-tests 665 | `e equality-assertion 666 | `e approximate-assertion 667 | `e exception-assertion 668 | `e setup 669 | `e teardown 670 | `e stronger-warnings 671 | `e suppress-warnings 672 | `e treat-warnings-as-errors 673 | `e run-debugger 674 | `e debugger-commands-help-list-source-re-load-executable-next-step-set-breakpoint-show-breakpoints-delete-breakpoint-continue-backtrace-up-stack-down-stack-print-run-quit 675 | `e benchmark-code 676 | `e profile-code 677 | `e memory-tool 678 | -------------------------------------------------------------------------------- /f-sharp.txt: -------------------------------------------------------------------------------- 1 | `e version-used 2 | F# 3.0 3 | Mono 3.2 4 | `e show-version 5 | $ fsharpi --help 6 | `e interpreter 7 | $ cat < hello.fs 8 | 9 | module hello 10 | 11 | let main = printfn "hello" 12 | 13 | EOF 14 | 15 | 16 | $ fsharpi --quiet --exec hello.fs 17 | `e shebang 18 | $ cat < hello.fs 19 | 20 | #light (* 21 | exec fsharpi --exec $0 --quiet 22 | 23 | *) 24 | 25 | 26 | module hello 27 | 28 | 29 | printfn "hello" 30 | 31 | EOF 32 | 33 | 34 | $ chmod +x hello.fs 35 | 36 | $ ./hello.fs 37 | `e bytecode-compiler-and-interpreter 38 | $ echo 'printfn "hello"' > hello.fs 39 | 40 | $ fsharpc hello.fs 41 | 42 | $ mono hello.exe 43 | `e native-compiler 44 | none 45 | `e library-which-is-always-imported 46 | Core 47 | `e statement-terminator 48 | ;; 49 | `e block-delimiters 50 | ( expr ; … ) 51 | 52 | begin expr ; … end 53 | `e end-of-line-comment 54 | // comment 55 | `e multiple-line-comment 56 | (* comment 57 | 58 | another comment *) 59 | `e constant 60 | let n = 1 + 2 61 | `e local-variable 62 | let n = ref 3 63 | 64 | n := 4 65 | 66 | !n + 7 67 | `e unit-type-and-value 68 | unit 69 | 70 | () 71 | `e conditional-expression 72 | let n = -3 73 | 74 | let absn = if n < 0 then -n else n 75 | `e branch-type-mismatch 76 | (* compilation error: *) 77 | 78 | if true then "hello" else 3 79 | `e null 80 | None 81 | 82 | Also this value returned by .NET library functions. It has a type distinct from None: 83 | 84 | null 85 | `e nullable-type 86 | 87 | `e null-test 88 | 89 | `e coalesce 90 | 91 | `e nullif 92 | 93 | `e expression-type-declaration 94 | float 1 95 | `e let-in 96 | let z = 97 | let x = 3.0 in 98 | let y = 2.0 * x in 99 | x * y 100 | `e where 101 | none 102 | `e boolean-type 103 | bool 104 | `e true-and-false 105 | true false 106 | `e logical-operators 107 | && || not 108 | `e relational-operators 109 | = <> < > <= >= 110 | `e min-and-max 111 | min 1 2 112 | 113 | max 1 2 114 | `e integer-type 115 | int 116 | 117 | other integer types: 118 | 119 | int32 int64 nativeint 120 | `e integer-literal 121 | -4 122 | `e float-type 123 | float 124 | `e integer-operators 125 | + - * / % 126 | `e float-operators 127 | + - * / 128 | `e add-integer-and-float 129 | float 3 + 7.0 130 | `e divmod 131 | 7 / 3 132 | 133 | 7 % 3 134 | `e integer-division-by-zero 135 | System.DivideByZeroException 136 | `e float-division 137 | float 7 / float 3 138 | `e float-division-by-zero 139 | infinity nan or neg_infinity 140 | `e power 141 | 2.0 ** 32.0 142 | `e sqrt 143 | sqrt 2.0 144 | `e sqrt-1 145 | nan 146 | `e transcendental-functions 147 | exp log 148 | 149 | sin cos tan 150 | 151 | asin acos atan atan2 152 | `e transcendental-constants 153 | System.Math.PI 154 | 155 | System.Math.E 156 | `e float-truncation 157 | truncate 3.14 158 | 159 | round 3.14 160 | 161 | floor 3.14 returns float 162 | 163 | ceil 3.14 returns float 164 | `e absolute-value-and-signum 165 | abs -7 166 | 167 | abs -7.0 168 | 169 | sign -7 170 | 171 | sign -7.0 172 | `e integer-overflow 173 | modular arithmetic 174 | `e float-overflow 175 | infinity 176 | `e arbitrary-length-integer 177 | // System.Numerics.BigInteger: 178 | 179 | let n = 7I 180 | 181 | let m = 12I 182 | `e arbitrary-length-integer-operators 183 | n + m 184 | 185 | n - m 186 | 187 | n * m 188 | 189 | n / m 190 | 191 | n % m 192 | 193 | 194 | n = m 195 | 196 | n < m 197 | 198 | n < m 199 | 200 | n <= m 201 | 202 | n >= m 203 | `e rational-type 204 | 205 | `e rational-construction 206 | 207 | `e rational-decomposition 208 | 209 | `e complex-type 210 | 211 | `e complex-constants 212 | 213 | `e complex-operators 214 | 215 | `e complex-construction 216 | System.Numerics.Complex(1.0, 2.0) 217 | `e complex-decomposition 218 | 219 | `e random-number-uniform-integer-uniform-float-normal-float 220 | let rnd = System.Random() 221 | 222 | 223 | rnd.Next(0, 100) 224 | 225 | rnd.NextDouble() 226 | none 227 | `e random-seed 228 | let rnd = System.Random(17) 229 | none 230 | none 231 | `e bit-operators 232 | 1 <<< 4 233 | 234 | 1 >>> 4 235 | 236 | 1 &&& 3 237 | 238 | 1 ||| 3 239 | 240 | 1 ^^^ 3 241 | ~~~ 1 242 | `e binary-octal-and-hex-literals 243 | 0b101010 244 | 245 | 0o52 246 | 247 | 0x2a 248 | `e radix-convert-integer-to-and-from-string-with-radix 249 | 250 | `e string-type 251 | string 252 | `e string-literal 253 | "Hello, World!" 254 | `e newline-in-literal 255 | yes 256 | `e literal-escapes 257 | \b \n \r\ t \" \' \\ 258 | 259 | \uhhhh \Uhhhhhhhh 260 | `e format 261 | sprintf "foo %s %d %.2f" "bar" 7 3.1415 262 | `e concatenate 263 | "Hello" + ", " + "World!" 264 | `e replicate 265 | String.replicate 80 "-" 266 | `e translate-case 267 | "hello".ToUpper() 268 | 269 | "HELLO".ToLower() 270 | `e capitalize 271 | 272 | `e trim 273 | " hello ".Trim() 274 | 275 | " hello".TrimStart() 276 | 277 | "hello ".TrimEnd() 278 | `e pad 279 | "hello".PadLeft(10, ' ') 280 | 281 | "hello".PadRight(10, ' ') 282 | `e number-to-string 283 | "two: " + string 2 284 | 285 | "pi: " + string 3.14 286 | `e string-to-number 287 | 7 + int "12" 288 | 289 | 73.9 + float ".037 290 | `e join 291 | System.String.Join(" ", ["do"; "re"; "mi"]) 292 | `e split 293 | "do re mi".Split(' ') 294 | `e character-type 295 | char 296 | `e character-literal 297 | 'h' 298 | `e string-length 299 | "hello".Length 300 | `e index-of-substring 301 | "hello".IndexOf("hell") 302 | `e extract-substring 303 | "hello".Substring(0, 4) 304 | `e extract-character 305 | "hello".[0] 306 | `e chr-and-ord 307 | int 'a' 308 | 309 | char 97 310 | `e date-time-type 311 | 312 | `e current-date-time 313 | 314 | `e current-unix-epoch 315 | 316 | `e literal 317 | 318 | `e size 319 | 320 | `e lookup 321 | 322 | `e update 323 | 324 | `e out-of-bounds 325 | 326 | `e literal 327 | [1; 2; 3] 328 | `e empty-list 329 | 330 | `e empty-test 331 | 332 | `e cons 333 | 1 :: [2; 3] 334 | `e head 335 | List.head [1; 2; 3] 336 | `e tail 337 | List.tail [1; 2; 3] 338 | `e head-and-tail-of-empty-list 339 | 340 | `e string-length 341 | List.length [1; 2; 3] 342 | `e list-lookup 343 | List.nth [1; 2; 3] 0 344 | `e index-of-element 345 | 346 | `e update 347 | 348 | `e concatenate-two-lists-list-of-lists 349 | [1; 2] @ [3; 4] 350 | 351 | List.append [1; 2] [3; 4] 352 | 353 | 354 | List.concat [[1; 2]; [3; 4]] 355 | `e last-and-butlast 356 | 357 | `e take 358 | 359 | `e drop 360 | 361 | `e iterate-over-elements 362 | let f i = 363 | System.Console.WriteLine(string i) 364 | 365 | 366 | List.iter f [1; 2; 3] 367 | `e reverse 368 | List.rev [1; 2; 3] 369 | `e sort 370 | List.sort [1; 3; 2; 4] 371 | `e map 372 | List.map (( * ) 2) [1; 2; 3] 373 | `e filter 374 | List.filter ((<) 2) [1; 2; 3] 375 | `e fold-from-left 376 | List.fold (-) 0 [1; 2; 3] 377 | `e fold-from-right 378 | 379 | `e membership 380 | 381 | `e universal-test 382 | List.forall (fun x -> x > 2) [1; 2; 3] 383 | `e existential-test 384 | List.exists (fun x -> x > 2) [1; 2; 3] 385 | `e zip-lists 386 | 387 | `e tuple 388 | (1, "hello", true) 389 | `e tuple-element-access 390 | match (1, "hello", true) with _, x, _ -> x 391 | `e pair-element-access 392 | fst (12, "December") 393 | 394 | snd (12, "December") 395 | `e define-function 396 | let average a b = ( a + b ) / 2.0 397 | `e invoke-function 398 | // 4.5: 399 | 400 | average 1.0 2.0 + 3.0 401 | 402 | // 3.0: 403 | 404 | average 1.0 (2.0 + 3.0) 405 | `e define-function-with-block-body 406 | 407 | `e named-parameters 408 | 409 | `e named-parameter-default-value 410 | 411 | `e piecewise-defined-function 412 | 413 | `e recursive-function 414 | 415 | `e mutually-recursive-functions 416 | 417 | `e lambda 418 | fun x -> fun y -> (x + y) / 2.0 419 | `e infix-operator-in-prefix-position 420 | 421 | `e function-in-infix-position 422 | 423 | `e currying 424 | 425 | `e composition 426 | 427 | `e function-composition-operator 428 | 429 | `e lazy-evaluation 430 | 431 | `e strict-evaluation 432 | default behavior 433 | `e if 434 | if x > 0 then 435 | printfn "pos" 436 | `e control-structure-keywords 437 | if x > 0 then 438 | printfn "pos" 439 | 440 | else 441 | if x < 0 then 442 | printfn "neg" 443 | else 444 | printfn "zero" 445 | `e sequencing 446 | printfn "one" 447 | 448 | printfn "two" 449 | 450 | printfn "three" 451 | `e while 452 | let i = ref 0 453 | 454 | 455 | while !i < 10 do 456 | printfn "%d" !i 457 | i := !i + 1 458 | `e for 459 | 460 | `e for-in-reverse 461 | 462 | `e list-iteration 463 | 464 | `e loop 465 | 466 | `e raise-error 467 | 468 | `e handle-error 469 | 470 | `e type-of-exceptions 471 | 472 | `e user-defined-exception 473 | 474 | `e standard-exceptions 475 | 476 | `e assert 477 | 478 | `e standard-file-handles 479 | stdin stdout stderr 480 | `e read-line-from-stdin 481 | 482 | `e end-of-file-behavior 483 | 484 | `e chomp 485 | 486 | `e write-line-to-stdout 487 | printfn "lorem ipsum" 488 | `e printf 489 | 490 | `e open-file-for-reading 491 | 492 | `e open-file-for-writing 493 | 494 | `e open-file-for-appending 495 | 496 | `e close-file 497 | 498 | `e i-o-errors 499 | 500 | `e read-line 501 | 502 | `e iterate-over-file-by-line 503 | 504 | `e read-file-into-array-of-strings 505 | 506 | `e read-file-into-string 507 | 508 | `e write-string 509 | 510 | `e write-line 511 | 512 | `e flush-file-handle 513 | 514 | `e end-of-file-test 515 | 516 | `e get-and-set-file-handle-position 517 | 518 | `e file-exists-test-regular-test 519 | 520 | `e file-size 521 | 522 | `e is-file-readable-writable-executable 523 | 524 | `e set-file-permissions 525 | 526 | `e copy-file-remove-file-rename-file 527 | 528 | `e create-symlink-symlink-test-readlink 529 | 530 | `e generate-unused-file-name 531 | 532 | `e build-pathname 533 | 534 | `e dirname-and-basename 535 | 536 | `e iterate-over-directory-by-file 537 | 538 | `e make-directory 539 | 540 | `e remove-empty-directory 541 | 542 | `e remove-directory-and-contents 543 | 544 | `e directory-test 545 | 546 | `e system-temporary-file-directory 547 | 548 | `e command-line-arguments 549 | 550 | `e program-name 551 | 552 | `e getopt 553 | 554 | `e get-and-set-environment-variable 555 | 556 | `e get-pid-parent-pid 557 | 558 | `e get-user-id-and-name 559 | 560 | `e exit 561 | 562 | `e set-signal-handler 563 | 564 | `e external-command 565 | 566 | `e escaped-external-command 567 | 568 | `e backticks 569 | 570 | `e namespace-example 571 | 572 | `e namespaces 573 | 574 | `e file-name-restrictions 575 | 576 | `e namespace 577 | 578 | `e namespace-creation 579 | 580 | `e namespace-alias 581 | 582 | `e namespace-separator 583 | 584 | `e subnamespace 585 | 586 | `e package-manager-setup 587 | 588 | `e package-manager-search-install-list-installed 589 | 590 | `e compile-app-using-package 591 | 592 | `e type-synonym 593 | type name = string 594 | `e sum-type 595 | type color = Red | Green | Blue 596 | 597 | 598 | let col = Red 599 | 600 | // evaluates to true: 601 | 602 | col < Green 603 | `e tuple-product-type-with-one-field 604 | type special_int = SpecialInt of int 605 | 606 | 607 | let n = SpecialInt 7 608 | `e tuple-product-type-with-two-fields 609 | type int_pair = IntPair of int * int 610 | 611 | 612 | let p = IntPair (7, 11) 613 | `e record-product-type 614 | type customer = { 615 | id: int; 616 | name: string; 617 | address: string 618 | 619 | } 620 | `e record-product-type-literal 621 | {id=7; name="John"; address="Topeka, KS"} 622 | `e generic-type 623 | type ('a, 'b) twosome = 624 | Twosome of 'a * 'b 625 | 626 | 627 | let p = Twosome ("pi", 3.14) 628 | `e recursive-type 629 | type binary_tree = 630 | | Leaf of int 631 | | Tree of binary_tree * binary_tree 632 | `e pattern-match-sum-type 633 | 634 | `e pattern-match-product-type 635 | 636 | `e pattern-match-guard 637 | 638 | `e pattern-match-catchall 639 | 640 | `e define-class 641 | 642 | `e create-object 643 | 644 | `e invoke-method 645 | 646 | `e field-access 647 | 648 | `e overload-function 649 | 650 | `e inheritance 651 | 652 | `e invoke-repl 653 | Mono: 654 | 655 | $ fsharpi 656 | 657 | In visual studio, highlight code and press ALT+ENTER. 658 | `e repl-limitations 659 | 660 | `e repl-last-value 661 | it 662 | `e help 663 | 664 | `e quit 665 | #quit;; 666 | `e inspect-type 667 | 668 | `e inspect-namespace 669 | 670 | `e load-source-file 671 | 672 | `e load-package 673 | 674 | `e search-path 675 | 676 | `e set-search-path-on-command-line 677 | 678 | -------------------------------------------------------------------------------- /groovy.txt: -------------------------------------------------------------------------------- 1 | `e version-used 2 | 2.2 3 | `e show-version 4 | $ groovy -v 5 | `e interpreter 6 | $ echo 'println "hi!"' > hi.groovy 7 | 8 | $ groovy hi.groovy 9 | `e repl 10 | $ groovysh 11 | `e command-line-program 12 | $ groovy -e 'println "hi world!"' 13 | `e block-delimiters 14 | {} 15 | `e statement-terminator 16 | newline or ; 17 | 18 | newline not a separator inside (), [], triple quote literal, or after binary operator or backslash. 19 | `e are-expressions-statements 20 | yes 21 | `e end-of-line-comment 22 | // comment 23 | `e multiple-line-comment 24 | /* comment 25 | 26 | another comment */ 27 | `e local-variable 28 | x = 1 29 | 30 | def y = 2 31 | 32 | Integer z = 3 33 | `e global-variable 34 | 35 | `e assignment 36 | x = 1 37 | `e parallel-assignment 38 | (x, y, z) = [1, 2, 3] 39 | 40 | // 3 is discarded: 41 | 42 | (x, y) = [1, 2, 3] 43 | 44 | // z is set to null: 45 | 46 | (x, y, z) = [1, 2] 47 | `e swap 48 | (x, y) = [y, x] 49 | `e null 50 | null 51 | `e null-test 52 | v == null 53 | `e uninitialized-local-variable 54 | raises groovy.lang.MissingPropertyException 55 | `e uninitialized-global-variable 56 | raises groovy.lang.MissingPropertyException 57 | `e conditional-expression 58 | x > 0 ? x : -x 59 | `e true-and-false 60 | true false 61 | `e falsehoods 62 | false null 0 0.0 "" [] [:] 63 | `e logical-operators 64 | && || ! 65 | `e relational-expression 66 | x > 0 67 | `e relational-operators 68 | == != > < >= <= 69 | `e min-and-max 70 | [1, 2, 3].min() 71 | 72 | [1, 2, 3].max() 73 | 74 | // binary functions: 75 | 76 | Math.min(1, 2) 77 | 78 | Math.max(1, 2) 79 | `e arithmetic-expression 80 | 1 + 3 81 | `e arithmetic-operators-addition-subtraction-multiplication-float-division-quotient-modulus 82 | + - * / ?? % 83 | `e integer-division 84 | Math.floor(x / y) 85 | `e integer-division-by-zero 86 | raises java.lang.ArithmeticException 87 | `e float-division 88 | x / y 89 | `e float-division-by-zero 90 | raises java.lang.ArithmeticException 91 | `e power 92 | 2 ** 32 93 | `e sqrt 94 | Math.sqrt(2) 95 | `e sqrt-1 96 | Double.NaN 97 | `e transcendental-functions 98 | Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2 99 | `e transcendental-constants 100 | Math.PI 101 | 102 | Math.E 103 | `e float-truncation 104 | (int)3.1 105 | 106 | Math.round(3.1) 107 | 108 | (int)Math.floor(3.1) 109 | 110 | (int)Math.ceil(3.1) 111 | `e absolute-value-and-signum 112 | Math.abs(-3) 113 | `e integer-overflow 114 | becomes type java.math.BigInteger 115 | `e float-overflow 116 | Double.POSITIVE_INFINITY 117 | `e random-number-uniform-integer-uniform-float-normal-float 118 | rnd = new Random() 119 | 120 | rnd.nextInt(100) 121 | 122 | rnd.nextDouble() 123 | `e random-seed 124 | rnd = new Random() 125 | 126 | rnd.setSeed(17) 127 | `e bit-operators 128 | << >> & | ^ ~ 129 | `e string-literal 130 | "don't say \"no\"" 131 | 132 | 'don\'t say "no"' 133 | 134 | """don't say "no\"""" 135 | 136 | '''don't say "no"''' 137 | 138 | /don't say "no"/ 139 | `e newline-in-literal 140 | // triple quote literals only: 141 | 142 | """foo 143 | 144 | bar""" 145 | 146 | 147 | '''foo 148 | 149 | bar''' 150 | `e literal-escapes 151 | // single and double quotes 152 | // including triple quotes: 153 | 154 | \b \f \n \r \t 155 | \\ \" \' 156 | 157 | \uhhhh \o \oo \ooo 158 | 159 | // slash quotes: 160 | 161 | \/ 162 | `e variable-interpolation 163 | count = 3 164 | 165 | item = "ball" 166 | 167 | 168 | "$count ${item}s" 169 | 170 | """$count ${item}s""" 171 | `e expression-interpolation 172 | "1 + 1 = ${1 + 1}" 173 | 174 | """1 + 1 = ${1 + 1}""" 175 | `e concatenate-strings 176 | s = "Hello, " + "World!" 177 | `e split 178 | "do re mi".split() 179 | `e join 180 | ["do", "re", "mi"].join(" ") 181 | `e format 182 | fmt = "lorem %s %d %.2f" 183 | 184 | String.format(fmt, "ipsum", 13, 3.7) 185 | `e translate-case 186 | "lorem".toUpperCase() 187 | 188 | "LOREM".toLowerCase() 189 | 190 | "lorem".capitalize() 191 | `e strip 192 | " lorem ".trim() 193 | `e pad 194 | "lorem".padRight(10) 195 | 196 | "lorem".padLeft(10) 197 | 198 | "lorem.center(10) 199 | `e string-to-number 200 | 7 + Integer.parseInt("12") 201 | 202 | 73.9 + Double.parseDouble(".037") 203 | `e number-to-string 204 | "value: " + 8 205 | 206 | // explicit conversion: 207 | 208 | 8.toString() 209 | `e string-length 210 | "lorem".size() 211 | 212 | "lorem".length() 213 | `e index-of-substring 214 | "lorem ipsum".indexOf("ipsum") 215 | `e extract-substring 216 | "lorem ipsum".substring(6, 11) 217 | `e chr-and-ord 218 | (Character)65 219 | 220 | (Integer)'A' 221 | `e character-class-abbreviations-and-anchors 222 | char class abbrevs: 223 | 224 | . \d \D \s \S \w \W 225 | 226 | anchors: ^ $ \b 227 | `e match-test 228 | s = "it is 1999" 229 | 230 | 231 | if (s =~ /1999/) { 232 | println("party!") 233 | 234 | } 235 | `e case-insensitive-match-test 236 | "Lorem" =~ /(?i)lorem/ 237 | `e modifiers 238 | i s 239 | `e substitution 240 | "do re mi mi mi".replaceAll(/mi/, "ma") 241 | `e group-capture 242 | s = "2010-06-03" 243 | 244 | m = s =~ /(\d{4})-(\d{2})-(\d{2})/ 245 | 246 | yr = m.group(1) 247 | 248 | mo = m.group(2) 249 | 250 | dy = m.group(3) 251 | `e backreference-in-match-and-substitution 252 | "do do" =~ /(\w+) \1/ 253 | 254 | 255 | rx = /(\w+) (\w+)/ 256 | 257 | "do re".replaceAll(rx, '$2 $1') 258 | `e current-date-time 259 | t = new Date() 260 | `e to-unix-epoch-from-unix-epoch 261 | Math.round(t.getTime() / 1000) 262 | 263 | t = new Date(1315716177 * 1000) 264 | `e strftime 265 | 266 | `e strptime 267 | 268 | `e parse-date-w-o-format 269 | 270 | `e date-parts 271 | 272 | `e time-parts 273 | 274 | `e build-date-time-from-parts 275 | 276 | `e sleep 277 | 278 | `e list-literal 279 | a = [1, 2, 3, 4] 280 | `e list-size 281 | a.size 282 | `e list-lookup 283 | a[0] 284 | `e list-update 285 | a[0] = 'lorem' 286 | `e list-out-of-bounds 287 | returns null 288 | `e index-of-element 289 | [6, 7, 7, 8].indexOf(7) 290 | 291 | [6, 7, 7, 8].lastIndexOf(7) 292 | // returns -1 if not found 293 | `e slice 294 | // ['b', 'c']: 295 | 296 | ['a', 'b', 'c', 'd'][1..2] 297 | `e drop 298 | // ['b', 'c', 'd']: 299 | 300 | ['a', 'b', 'c', 'd'][1..-1] 301 | `e concatenate 302 | [1, 2, 3] + [4, 5, 6] 303 | `e list-replicate 304 | a = [null] * 10 305 | `e manipulate-back 306 | a = [6, 7, 8] 307 | 308 | a.push(9) 309 | // also: 310 | 311 | a << 9 312 | 313 | i = a.pop() 314 | `e manipulate-front 315 | a = [6, 7, 8] 316 | 317 | a.add(0, 5) 318 | 319 | i = a.remove(0) 320 | `e iterate-over-elements 321 | for (i in [1, 2, 3, 4]) { 322 | println i 323 | 324 | } 325 | `e reverse 326 | a = [1, 2, 3] 327 | 328 | a.reverse() 329 | `e sort 330 | a = [3, 1, 4, 2] 331 | 332 | a.sort() 333 | `e dedupe 334 | a = [1, 2, 2, 3] 335 | 336 | // modifies array in place: 337 | 338 | a.unique() 339 | `e membership 340 | [1, 2, 3].contains(7) 341 | 342 | ![1, 2, 3].contains(7) 343 | `e intersection 344 | [1, 2].intersect([2, 3]) 345 | `e union 346 | ([1, 2] + [2, 3, 4]).unique() 347 | `e relative-complement-symmetric-difference 348 | [1 2 3] - [2] 349 | `e map 350 | [1, 2, 3].collect() { n -> n * n } 351 | `e filter 352 | [1, 2, 3].findAll() { x -> x > 2 } 353 | `e fold-from-left 354 | [1, 2, 3].inject(0) { x, y -> x + y } 355 | `e shuffle-and-sample 356 | a = [1, 2, 3, 4] 357 | // no return value: 358 | 359 | Collections.shuffle(a) 360 | `e zip 361 | [[1,2,3], ['a', 'b', 'c']].transpose() 362 | `e map-literal 363 | d = ["t": 1, "f": 0] 364 | `e map-size 365 | d.size() 366 | `e map-lookup 367 | d["t"] 368 | `e map-update 369 | d["t"] = 2 370 | `e map-out-of-bounds 371 | returns null 372 | `e is-key-present 373 | d.containsKey("t") 374 | `e delete 375 | 376 | `e iteration 377 | 378 | `e declare-function 379 | def (x, y) { 380 | x + y 381 | 382 | } 383 | `e invoke-function 384 | add(1, 2) 385 | 386 | // parens are optional: 387 | 388 | add 1, 2 389 | `e missing-argument-behavior 390 | raises groovy.lang.MissingMethodException 391 | `e extra-arguments 392 | raises groovy.lang.MissingMethodException 393 | `e default-value 394 | 395 | `e variable-number-of-arguments 396 | 397 | `e return-value 398 | return arg or last expression evaluated 399 | `e multiple-return-values 400 | none 401 | `e lambda 402 | sqr = { x -> Math.sqrt x } 403 | `e lambda-invocation 404 | sqr(2) 405 | `e default-scope 406 | 407 | `e nested-function-visibility 408 | 409 | `e if 410 | if (n == 0) { 411 | println("no hits") 412 | 413 | } 414 | 415 | else if (n == 1) { 416 | println("one hit") 417 | 418 | } 419 | 420 | else { 421 | println(n + " hits") 422 | 423 | } 424 | `e while 425 | while (i < 100) { 426 | i += 1 427 | 428 | } 429 | `e break-continue-redo 430 | break continue 431 | `e for 432 | for (i = 0; i < 10; i++) { 433 | println i 434 | 435 | } 436 | `e raise-exception 437 | throw new Exception("bad arg") 438 | `e catch-exception 439 | 440 | `e finally 441 | 442 | `e uncaught-exception-behavior 443 | 444 | `e generator 445 | 446 | `e standard-file-handles 447 | System.in 448 | 449 | System.out 450 | 451 | System.err 452 | `e read-line-from-stdin 453 | 454 | `e write-line-to-stdout 455 | print("Hello, World!\n") 456 | 457 | println("Hello, World!") 458 | 459 | System.out.print("Hello, World!\n") 460 | 461 | System.out.println("Hello, World!") 462 | `e open-file-for-reading 463 | 464 | `e open-file-for-writing 465 | 466 | `e close-file 467 | 468 | `e read-line 469 | 470 | `e iterate-over-file-by-line 471 | 472 | `e chomp 473 | 474 | `e read-file 475 | 476 | `e write-to-file 477 | 478 | `e flush-file-handle 479 | 480 | `e file-exists-test-regular-test 481 | f = new File('/etc/hosts') 482 | 483 | 484 | f.exists() 485 | 486 | f.isFile() 487 | `e file-size 488 | f = new File('/etc/hosts') 489 | 490 | 491 | f.length() 492 | `e is-file-readable-writable-executable 493 | f = new File('etc/hosts') 494 | 495 | 496 | f.canRead() 497 | 498 | f.canWrite() 499 | 500 | f.canExecute() 501 | `e copy-file-remove-file-rename-file 502 | 503 | `e set-file-permissions 504 | 505 | `e temporary-file 506 | 507 | `e build-pathname 508 | 509 | `e dirname-and-basename 510 | 511 | `e iterate-over-directory-by-file 512 | 513 | `e make-directory 514 | 515 | `e remove-empty-directory 516 | 517 | `e remove-directory-and-contents 518 | 519 | `e directory-test 520 | 521 | `e command-line-arguments 522 | args.size() 523 | 524 | args[0] 525 | 526 | args[1] 527 | 528 | … 529 | `e environment-variable 530 | System.getenv("HOME") 531 | `e exit 532 | System.exit(0) 533 | `e external-command 534 | 535 | `e backticks 536 | 537 | `e library 538 | 539 | `e import-library 540 | 541 | `e library-path 542 | 543 | `e library-path-environment-variable 544 | 545 | `e declare-namespace 546 | 547 | `e namespace-separator 548 | 549 | `e list-installed-packaged-install-a-package 550 | 551 | `e define-class 552 | class Int { 553 | public int value 554 | Int (int n) { 555 | value = n 556 | } 557 | 558 | } 559 | `e create-object 560 | o = new Int(3) 561 | `e create-blank-object 562 | 563 | `e set-attribute 564 | o.value = 4 565 | `e get-attribute 566 | o.value 567 | `e define-method 568 | 569 | `e invoke-method 570 | 571 | `e clone-object 572 | 573 | `e object-literal 574 | 575 | `e inspect-type 576 | o.class 577 | 578 | o.getClass() 579 | `e has-method 580 | 581 | `e message-passing 582 | 583 | `e eval 584 | 585 | `e inspect-methods 586 | "lorem".metaClass.methods 587 | `e inspect-attributes 588 | 589 | -------------------------------------------------------------------------------- /harvest.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from bs4 import BeautifulSoup, NavigableString 3 | import sys, codecs, re 4 | 5 | def textish(node): 6 | for d in node.descendants: 7 | if isinstance(d, NavigableString): 8 | yield unicode(d).replace("\n", "") 9 | elif d.name == "br": 10 | yield "\n" 11 | 12 | def get_surroundings(style): 13 | if "purple" in style: return "`*" 14 | if "teal" in style: return "`." 15 | if "maroon" in style: return "`=" 16 | if "gray" in style: return "`c" 17 | return None 18 | 19 | def marked_text(node): 20 | for d in node.children: 21 | if isinstance(d, NavigableString): 22 | yield unicode(d).replace("\n", "").replace("`","``") 23 | elif d.name == "br": 24 | yield "\n" 25 | else: 26 | try: 27 | sur = get_surroundings(d["style"]) 28 | except KeyError: 29 | sur = None 30 | if sur: yield sur 31 | needBracket = False 32 | buf = [] 33 | for t in marked_text(d): 34 | if sur and not needBracket and all(c.isalnum() or c == '_' for c in t): 35 | buf.append(t) 36 | else: 37 | if sur and not needBracket: 38 | needBracket = True 39 | yield "[" 40 | for tt in buf: yield tt 41 | yield t 42 | for tt in buf: yield tt 43 | if sur and needBracket: yield "]" 44 | 45 | overrides = { 46 | "statement-separator": "statement-terminator", 47 | "blocks": "block-delimiters", 48 | "modifiable-variable": "local-variable", 49 | "write-once-variable": "constant", 50 | "arithmetic-operators-addition-subtraction-multiplication-float-division-quotient-remainder": "arithmetic-operators", 51 | "compound-assignment-arithmetic-bit": "compound-assignment-arithmetic-string-logical-bit", 52 | "integer-division-and-remainder": "divmod", 53 | "transcendental-constants-and-e": "transcendental-constants", 54 | "float-truncation-towards-zero-to-nearest-integer-towards-towards": "float-truncation", 55 | "float-truncation-round-towards-zero-round-to-nearest-integer-round-down-round-up": "float-truncation", 56 | "random-number-uniform-int-uniform-float-normal-float": "random-number-uniform-integer-uniform-float-normal-float", 57 | "random-seed-set-get-restore": "random-seed", 58 | "random-seed-how-to-set": "random-seed", 59 | "bit-operators-left-shift-right-shift-and-inclusive-or-exclusive-or-complement": "bit-operators", 60 | "radix": "radix-convert-integer-to-and-from-string-with-radix", 61 | "character-escapes": "literal-escapes", 62 | "translate-case-to-upper-to-lower": "translate-case", 63 | "case-manipulation": "translate-case", 64 | "format-string": "format", 65 | "string-concatenation": "concatenate-strings", 66 | "trim-both-sides-left-right": "trim", 67 | "pad-on-left-on-right": "pad", 68 | "pad-on-left-on-right-centered": "pad", 69 | "pad-on-right-on-left-centered": "pad", 70 | "pad-on-right-on-left": "pad", 71 | "length": "string-length", 72 | "index-of-substring-first-last": "index-of-substring", 73 | "extract-substring-by-start-and-length-by-start-and-end-by-successive-starts": "extract-substring", 74 | "date-and-time-type": "date-time-type", 75 | "date-and-time-types": "date-time-type", 76 | "current-date-and-time": "current-date-time", 77 | "result-of-date-subtraction": "date-subtraction", 78 | "add-time-duration": "add-duration", 79 | "date-parts": "date-parts", 80 | "time-parts": "time-parts", 81 | "empty-list-test": "empty-test", 82 | "nth-element": "list-lookup", 83 | "element-index": "index-of-element", 84 | "shuffle": "shuffle-and-sample", 85 | "index-of-element-first-and-last-occurrence": "index-of-element", 86 | "slice-by-endpoints-by-length": "slice", 87 | "backreference-in-regex-in-substitution-string": "backreference-in-match-and-substitution", 88 | "get-date-parts": "date-parts", 89 | "get-time-parts": "time-parts", 90 | "dict-literal": "map-literal", 91 | "dict-size": "map-size", 92 | "replicate-element": "replicate", 93 | "relative-complement": "relative-complement-symmetric-difference", 94 | "function-declaration": "declare-function", 95 | "function-invocation": "invoke-function", 96 | "named-parameter": "named-parameters", 97 | "missing-argument-value": "missing-argument-behavior", 98 | "if-else-if-else": "control-structure-keywords", 99 | "break-and-continue": "break-continue-redo", 100 | "copy-address-copy-shallow-copy-deep-copy": "copy", 101 | "sort-non-destructive-in-place-custom-comparision": "sort", 102 | "dedupe-non-destructive-in-place": "dedupe", 103 | "finally-ensure": "finally", 104 | "finally-clause": "finally", 105 | "namespace-declaration": "declare-namespace", 106 | "write-formatted-string-to-stdout": "printf", 107 | "file-test-regular-file-test": "file-exists-test-regular-file-test", 108 | "temporary-directory": "system-temporary-file-directory", 109 | "class-definition": "define-class", 110 | "object-creation": "create-object", 111 | "method-invocation": "invoke-method", 112 | "typedef": "type-synonym", 113 | "get-and-set-filehandle-position": "get-and-set-file-handle-position", 114 | "file-exists-test-file-regular-test": "file-exists-test-regular-test", 115 | "file-exists-test-regular-file-test": "file-exists-test-regular-test", 116 | "pad-on-right-on-left-centered": "pad", 117 | "complex-decomposition-real-and-imaginary-component-argument-absolute-value-conjugate": "complex-decomposition", 118 | "float-division-by-zero-dividend-is-positive-zero-negative": "float-division-by-zero", 119 | "version-used": "versions-used", 120 | "add-time-duration": "add-duration", 121 | "open-temporary-file": "temporary-file", 122 | } 123 | def normalize(e): 124 | h = re.sub(r'\W+', '-', e.lower()).strip('-') 125 | return overrides.get(h, h) 126 | 127 | def parse_entries(filename, outfilename, append=True): 128 | with codecs.open(filename, 'r', encoding="utf-8") as infile: 129 | with codecs.open(outfilename, 'a' if append else 'w', encoding="utf-8") as outfile: 130 | outfile.write('# general\n') 131 | soup = BeautifulSoup(infile, "html.parser") 132 | t = soup.table 133 | for row in t.find_all('tr'): 134 | ths = row.find_all('th') 135 | if ths and ths[0].get('colspan'): 136 | outfile.write('# ') 137 | outfile.write(''.join(textish(ths[0])).strip().replace('\n', ' / ')) 138 | outfile.write('\n') 139 | tds = row.find_all('td') 140 | if tds: 141 | name = ''.join(textish(tds[0])).strip().replace('\n', ' / ') 142 | e = normalize(name) 143 | outfile.write(e) 144 | outfile.write(': ') 145 | outfile.write(name) 146 | outfile.write('\n') 147 | 148 | def parse(filename, colfilenames): 149 | colfiles = [codecs.open(fn, 'w', encoding="utf-8") for fn in colfilenames] 150 | 151 | with codecs.open(filename, encoding="utf-8") as infile: 152 | soup = BeautifulSoup(infile, "html.parser") 153 | t = soup.table 154 | for row in t.find_all('tr'): 155 | tds = row.find_all('td') 156 | if tds: 157 | for f in colfiles: 158 | name = ''.join(textish(tds[0])) 159 | e = normalize(name) 160 | if e: 161 | f.write('`e ') 162 | f.write(e) 163 | f.write('\n') 164 | for td, f in zip(tds[1:], colfiles): 165 | for txt in marked_text(td): 166 | f.write(txt.replace(u'\xa0', u' ')) 167 | f.write('\n') 168 | for f in colfiles: f.close() 169 | 170 | # to_parse_entries = [('scripting.html', 'entries.txt', False),('cpp.html', 'entries.txt'),('c.html', 'entries.txt'),('pascal.html', 'entries.txt'),('lisp.html', 'entries.txt'),('ml.html', 'entries.txt')] 171 | # to_parse_entries = [('ml.html', 'entries.ml.txt', False)] 172 | # to_parse_entries = [('scripting2.html', 'scripting2.txt')] 173 | to_parse_entries = [] 174 | # to_parse = [('scripting.html', ['perl.txt', 'php.txt', 'python.txt', 'ruby.txt']),('more.html', ['tcl.txt', 'lua.txt', 'javascript.txt', 'groovy.txt']),('cpp.html', ['cpp.txt', 'objective-c.txt', 'java.txt', 'c-sharp.txt']),('c.html', ['c.txt', 'go.txt']),('pascal.html', ['pascal.txt', 'ada.txt', 'plpgsql.txt']),('lisp.html', ['common-lisp.txt', 'racket.txt', 'clojure.txt', 'emacs-lisp.txt']),('ml.html', ['ocaml.txt', 'f-sharp.txt', 'scala.txt', 'haskell.txt']),('logic.html', ['prolog.txt', 'erlang.txt']),('stack.html', ['forth.txt', 'postscript.txt', 'factor.txt']),('shell.html', ['posix-shell.txt', 'applescript.txt', 'powershell.txt']),('data.html', ['sql.txt', 'awk.txt', 'pig.txt']),('numerical-analysis.html', ['matlab.txt', 'r.txt', 'numpy.txt']),('fortran.html', ['fortran.txt']),('computer-algebra.html', ['mathematica.txt', 'sympy.txt', 'maxima.txt', 'pari-gp.txt']),] 175 | # to_parse = [('ml.html', ['sml-new.txt', 'ocaml-new.txt', 'f-sharp-new.txt', 'haskell-new.txt'])] 176 | # to_parse = [('scripting2.html', ['perl2.txt', 'php2.txt', 'python2.txt', 'ruby2.txt'])] 177 | # to_parse = [('rust.html', ['rust.txt', 'swift.txt', 'scala2.txt'])] 178 | to_parse = [('more.html', ['perl2.txt', 'lua2.txt', 'groovy.txt'])] 179 | # to_parse = [('more.html', ['tcl.txt', 'lua.txt', 'javascript.txt', 'groovy.txt'])] 180 | # to_parse = [('lisp.html', ['common-lisp.txt', 'racket.txt', 'clojure.txt', 'emacs-lisp.txt'])] 181 | 182 | for ix, t in enumerate(to_parse_entries): 183 | print("{}/{} parsing entries {}...".format(ix + 1, len(to_parse_entries), t[0]), end="") 184 | parse_entries(*t) 185 | print(" OK") 186 | 187 | print() 188 | 189 | for ix, t in enumerate(to_parse): 190 | print("{}/{} parsing {}...".format(ix + 1, len(to_parse), t[0]), end="") 191 | parse(*t) 192 | print(" OK") 193 | -------------------------------------------------------------------------------- /haskell.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | 7.4 3 | `e show-version 4 | `$[ghc --version] 5 | `e hello-world 6 | main = putStrLn `=["hello"] 7 | `e file-suffixes 8 | .hs .lhs 9 | `c[none] 10 | .o 11 | `e interpreter 12 | `$[echo 'main = putStrLn "hello"' > hello.hs] 13 | `$[runghc hello.hs] 14 | `e shebang 15 | `$[cat < hello.hs 16 | #!/usr/bin/env runghc 17 | main = putStrLn "hello" 18 | EOF] 19 | `$[chmod +x hello.hs] 20 | `$[./hello.hs] 21 | `e bytecode-compiler-and-interpreter 22 | `e native-compiler 23 | `$[echo 'main = putStrLn "hello"' > hello.hs] 24 | `$[ghc -o hello hello.hs] 25 | `$[./hello] 26 | `e library-which-is-always-imported 27 | Prelude 28 | `e statement-terminator 29 | next line has equal or less indentation, or ; 30 | `e block-delimiters 31 | offside rule or { } 32 | `e end-of-line-comment 33 | -- comment 34 | `e multiple-line-comment 35 | {- comment 36 | another comment -} 37 | `e constant 38 | n = 3 39 | `e local-variable 40 | `c[Haskell is purely functional and all normal variables are immutable. A maximally functional version of mutable variables may be simulated with Control.Monad.Trans.State, of the transformers package:] 41 | `*import Control.Monad.Trans.State 42 | evalState (`*do 43 | set 4 44 | modify (+1) 45 | fmap (+7) get) 3 46 | `c[runState returns (result, state]; evalState returns result; execState returns state) 47 | `c[A more destructive version uses STRefs in a STRef monad or IORefs in the IO monad:] 48 | `*import Data.IORef 49 | `*do 50 | n `+[<-] newIORef 3 51 | writeIORef n 4 52 | fmap (+7) $ readIORef n 53 | 54 | `*import Data.STRef 55 | `*import Control.Monad.ST 56 | runST $ `*do 57 | n `+[<-] newSTRef 3 58 | writeSTRef n 4 59 | fmap (+7) $ readSTRef n 60 | `e unit-type-and-value 61 | () 62 | () 63 | `e conditional-expression 64 | n = -3 65 | `*let absn = `*if n < 0 `*then -n `*else n 66 | `e branch-type-mismatch 67 | `![compilation error:] 68 | `*if `=True `*then "hello" `*else 3 69 | `e null 70 | `.Nothing `c[type Maybe a] 71 | `e nullable-type 72 | list = [`.Just 3, `.Nothing, `.Just (-4)] 73 | `e null-test 74 | `*import Data.Maybe 75 | 76 | isJust v 77 | `e coalesce 78 | `*import Data.Maybe 79 | 80 | `*let foo = `.Just 3 81 | `*let intId x = x 82 | 83 | `![raises exception if `.Nothing:] 84 | fromJust foo 85 | 86 | `![evaluates to 0 if `.Nothing:] 87 | maybe 0 intId foo 88 | fromMaybe 0 foo 89 | `e nullif 90 | 91 | `e expression-type-declaration 92 | 1 `+[::] `=Double 93 | `e let-in 94 | z = `*let x = 3.0 95 | y = 2.0 * x 96 | `*in x * y 97 | `e where 98 | z = x * y 99 | `*where x = 3.0 100 | y = 2.0 * x 101 | `e boolean-type 102 | `.Bool 103 | `e true-and-false 104 | `=True `=False 105 | `e falsehoods 106 | `=False 107 | `e logical-operators 108 | && || not 109 | `e relational-operators 110 | == /= < > <= >= 111 | `e compare-strings 112 | == /= < > <= >= 113 | `e three-value-comparison 114 | 0 ``compare`` 1 `c[returns value of type Ordering, one of LT, EQ, or GT] 115 | `e min-and-max 116 | min 1 2 117 | max 1 2 118 | `e integer-type 119 | `.Int `c[fixed-width] 120 | `.Integer `c[arbitrary length] 121 | `e integer-literal 122 | an expression, not a literal: 123 | 124 | -4 125 | `e float-type 126 | Double 127 | `e integer-operators 128 | + - * ``quot`` ``rem`` ``div`` ``mod`` 129 | `c[the last four are functions, not infix operators, although they are often used as infix operators by surrounding with backquotes. quot truncates towards 0 and rem's value has the same sign as the dividend; div truncates down and mod returns a nonnegative result.] 130 | `e float-operators 131 | `+[+ - * /] 132 | `e add-integer-and-float 133 | `c[integer literals are parsed as floats in such contexts:] 134 | 3 + 7.0 135 | `c[integers can be converted with fromIntegral:] 136 | x = 3 `+[::] Int 137 | fromIntegral x + 7.0 138 | `e divmod 139 | 7 ``quotRem`` 3 140 | 7 ``divMod`` 3 141 | `e integer-division-by-zero 142 | `![Exception: divide by zero] 143 | `e float-division 144 | 7 / 3 145 | `e float-division-by-zero 146 | evaluates to Infinity, NaN, or -Infinity, values which do not have literals 147 | `e power 148 | 2 ^ 32 `c[integer powers only] 149 | 2 ^^ 32 `c[fractional base, integer powers only] 150 | 2 ** 32 `c[same-type floating base and exponent] 151 | `e sqrt 152 | sqrt 2 153 | `e sqrt-1 154 | sqrt (-1) `c[evaluates to NaN, a value which has no literal] 155 | `e transcendental-functions 156 | exp log 157 | 158 | sin cos tan 159 | 160 | asin acos atan atan2 161 | `e transcendental-constants 162 | pi 163 | 164 | exp 1 165 | `e float-truncation 166 | truncate 3.14 167 | round 3.14 168 | floor 3.14 169 | ceiling 3.14 170 | `e absolute-value-and-signum 171 | abs (-7) 172 | signum (-7) 173 | `e integer-overflow 174 | `.Int wraps; `.Integer is arbitrary length 175 | `e float-overflow 176 | evaluates to Infinity, a value which has no literal 177 | `e arbitrary-length-integer 178 | `c[Integer is arbitrary length type, and assumed by default for numbers in contexts where no other type restrictions can be inferred.] 179 | `*let n = 7 `+[::] `.Integer 180 | `c[Note that an integer literal is polymorphic, as is a function defined as a single integer literal.] 181 | `*let m = 12 182 | `e arbitrary-length-integer-operators 183 | n + m 184 | n - m 185 | n * m 186 | quot n m `c[or] div n m 187 | rem n m `c[or] mod n m 188 | 189 | n == m 190 | n < m 191 | n > m 192 | n <= m 193 | n >= m 194 | `e rational-type 195 | Ratio Integer 196 | `e rational-construction 197 | `*import Data.Ratio 198 | 199 | 1 % 7 200 | (1 / 7) `+[::] Rational 201 | `e rational-decomposition 202 | `*import Data.Ratio 203 | 204 | numerator (1 % 7) 205 | denominator (1 % 7) 206 | `e complex-type 207 | Complex Double 208 | `e complex-constants 209 | 210 | `e complex-operators 211 | 212 | `e complex-construction 213 | `*import Data.Complex 214 | 215 | 1 :+ 2.0 216 | `e complex-decomposition 217 | `*import Data.Complex 218 | 219 | realPart (1 :+ 2) 220 | imagPart (1 :+ 2) 221 | phase (1 :+ 2) 222 | magnitude (1 :+ 2) 223 | conjugate (1 :+ 2) 224 | `e random-number-uniform-integer-uniform-float-normal-float 225 | `$[cabal install random] 226 | 227 | `*import System.Random 228 | 229 | getStdRandom (randomR (0, 99)) 230 | getStdRandom (randomR (0.0, 1.0)) 231 | none 232 | `e random-seed 233 | `$[cabal install random] 234 | 235 | `*import System.Random 236 | 237 | setStdGen $ mkStdGen 17 238 | 239 | seed `+[<-] getStdGen 240 | 241 | setStdGen seed 242 | `e bit-operators 243 | `*import Data.Bits 244 | 245 | x = 1 `+[::] Integer 246 | y = 3 `+[::] Integer 247 | 248 | 249 | shiftL x 4 250 | shiftR x 4 251 | x .&. y 252 | x .|. y 253 | xor x y 254 | complement x 255 | `e binary-octal-and-hex-literals 256 | `c[none] 257 | 052 258 | 0x2a 259 | `e radix-convert-integer-to-and-from-string-with-radix 260 | `*import Data.Char 261 | `*import Numeric 262 | showIntAtBase 7 intToDigit 42 "" 263 | `*case readInt 7 isDigit digitToInt "60" `*of 264 | [(n, "")] `+[->] n 265 | _ `+[->] error "Parse failed" 266 | `e string-type 267 | String `c[alias for [Char]] 268 | `e string-literal 269 | `=["Hello, World!"] 270 | `e newline-in-literal 271 | no 272 | `e literal-escapes 273 | \a \b \f \n \r \t \v \" \& \' \\ 274 | 275 | \oo... \d... \xh... 276 | 277 | Octal, decimal, and hex escapes denote Unicode characters and can contain anywhere from 1 to 7 digits. The max values are \o4177777, \1114111, and \x10ffff. The \& escape does not represent a character, but can separate a numeric backslash escape sequence from a following digit. 278 | `e are-strings-mutable 279 | no 280 | `e format 281 | `*import Text.Printf 282 | 283 | printf "foo %s %d %.2f" "bar" 7 3.1415 284 | `e concatenate-strings 285 | "Hello" ++ ", " ++ "World!" 286 | `e replicate-string 287 | concat $ replicate 80 "-" 288 | replicate 80 '-' 289 | `e translate-case 290 | `*import Data.Char 291 | 292 | map toUpper "hello" 293 | map toLower "HELLO" 294 | `e capitalize 295 | 296 | `e trim 297 | 298 | `e pad 299 | 300 | `e number-to-string 301 | "two: " ++ (show 2) 302 | "pi: " ++ (show 3.14) 303 | `e string-to-number 304 | `![raises exception if string doesn't completely parse:] 305 | 7 + (read "12")`+[::]Integer 306 | 73.9 + (read "0.037")`+[::]Double 307 | 308 | `c[reads returns a list of (parsed value, remaining string] pairs, or an empty list if parsing fails:) 309 | reads "12" `+[::] [(Int, String)] 310 | `*case reads "12" `*of 311 | [(x, "")] `+[->] 7 + x 312 | `+_ `+[->] error "Parse failed" 313 | 314 | `c[GHC 7.6:] 315 | `*import Text.Read 316 | fmap (7 +) $ readMaybe "12" 317 | fmap (73.9 +) $ readEither "0.037" 318 | `e join 319 | unwords ["do", "re", "mi", "fa"] `c[join by spaces] 320 | `*import Data.List 321 | intercalate " " ["do", "re", "mi", "fa"] 322 | 323 | `e split 324 | `c[on whitespace:] 325 | words "do re mi fa" 326 | `e character-type 327 | `.Char 328 | `e character-literal 329 | `=['h'] 330 | `e string-length 331 | length "hello" `c[type Int] 332 | `e index-of-substring 333 | 334 | `e extract-substring 335 | drop 0 (take 4 "hello") 336 | `e extract-character 337 | "hello" !! 0 338 | `e chr-and-ord 339 | Char.ord 'a' 340 | Char.chr 97 341 | `e to-array-of-characters 342 | `c[strings are exactly the same as lists of characters] 343 | `e date-time-type 344 | ClockTime CalendarTime TimeDiff 345 | `e current-date-time 346 | `*import Time 347 | 348 | t `+[<-] getClockTime 349 | `e current-unix-epoch 350 | `*import System.Time 351 | 352 | 353 | getClockTime >>= (`+\(TOD sec `+_) `+[->] return sec) 354 | `e declare-on-heap 355 | 356 | `e array-initialization-list 357 | `*import Data.Array 358 | a = listArray (0, 2) [1, 2, 3] 359 | `e array-size 360 | `c[returns smallest and largest valid index:] 361 | bounds a 362 | `e array-lookup 363 | n = a ! 0 364 | `e array-update 365 | `c[returns updated copy:] 366 | a // [(2, 4)] 367 | `e array-out-of-bounds 368 | `![exception] 369 | `e array-iterate 370 | `c[purely functional map:] 371 | fmap `c[function] a 372 | `c[for monadic iteration, first convert to list with elems or assocs:] 373 | mapM_ (`+\e `+[->] print e) $ elems a 374 | mapM_ (`+\(i,e) `+[->] printf "%d at index %d\n" e i) $ assocs a 375 | `e list-name 376 | [] 377 | `e list-literal 378 | [1, 2, 3] 379 | `e list-size 380 | length [1, 2, 3] 381 | `e empty-list 382 | [] 383 | `e empty-test 384 | `*let list = [1, 2, 3] 385 | 386 | list == [] 387 | null list 388 | `c[pattern matching can often be used to avoid these constructions:] 389 | `*case list `*of 390 | (x:xs) = x + 1 391 | [] = error "empty list" 392 | `e cons 393 | 1 : [2, 3] 394 | `e head 395 | head [1, 2, 3] 396 | `e tail 397 | tail [1, 2, 3] 398 | `e head-and-tail-of-empty-list 399 | exceptions 400 | `e list-size 401 | length [1, 2, 3] 402 | `e list-lookup 403 | [1, 2, 3] !! 0 404 | `e index-of-element 405 | `*import Data.list 406 | 407 | `c[Just 1:] 408 | elemIndex 8 [7, 8, 9] 409 | 410 | `c[Nothing:] 411 | elemIndex 10 [7, 8, 9] 412 | `e update 413 | 414 | `e concatenate 415 | [1, 2] ++ [3, 4] 416 | `e concatenate-two-lists-list-of-lists 417 | [1, 2] ++ [3, 4] 418 | concat [[1, 2], [3, 4]] 419 | `e list-replicate 420 | a = replicate 10 Nothing 421 | `e last-and-butlast 422 | last [1, 2, 3] 423 | init [1, 2, 3] 424 | `e take 425 | take 2 [1, 2, 3] 426 | `e drop 427 | drop 2 [1, 2, 3] 428 | `e iterate-over-elements 429 | mapM_ print [1, 2, 3] 430 | forM_ [1, 2, 3] print 431 | `e iterate-over-indices-and-elements 432 | mapM_ (uncurry $ printf "%s at index %d\n") $ zip ["do", "re", "mi", "fa"] [0..] 433 | `e iterate-over-range 434 | forM_ [1..1000000] `c[IO monad expression] 435 | `e instantiate-range-as-list 436 | [1..1000000] `c[sugar for:] enumFromTo 1 1000000 437 | `e reverse 438 | reverse [1, 2, 3] 439 | `e sort 440 | `*import Data.List 441 | sort [1, 3, 2, 4] 442 | sortBy (`+\x y `+[->] x ``compare`` y) [1, 3, 2, 4] 443 | sortBy (`+\x y `+[->] y ``compare`` x) [1, 3, 2, 4] 444 | 445 | `*import Data.Ord 446 | sortBy (comparing id) [1, 3, 2, 4] 447 | sortBy (comparing Down) [1, 3, 2, 4] `c[Down is newtype that reverses orderings] 448 | `e dedupe 449 | `*import Data.List 450 | a = [1, 2, 2, 3] 451 | nub a 452 | `e map 453 | map (`+\x `+[->] x * x) [1, 2, 3] 454 | `c[or use list comprehension:] 455 | [x * x | x `+[<-] [1, 2, 3]] 456 | `e filter 457 | filter (`+\x `+[->] x > 2) [1, 2, 3] 458 | `c[or use list comprehension:] 459 | [x | x `+[<-] [1, 2, 3], x > 2] 460 | `e fold-from-left 461 | foldl (+) 0 [1, 2, 3] 462 | foldl' (+) 0 [1, 2, 3] `c[strict variant] 463 | `e fold-from-right 464 | foldr (-) 0 [1, 2, 3] 465 | `e membership 466 | elem 3 [1, 2, 3] 467 | `e universal-test 468 | all (`+\x `+[->] x > 2) [1, 2, 3] 469 | `e existential-test 470 | any (`+\x `+[->] x > 2) [1, 2, 3] 471 | `e intersection 472 | `*import Data.List 473 | intersect [1, 2] [2, 3, 4] 474 | `e union 475 | `*import Data.List 476 | union [1, 2] [2, 3, 4] 477 | `e relative-complement-symmetric-difference 478 | `*import Data.List 479 | [1, 2] \\ [2, 3, 4] 480 | `e min-and-max-element 481 | `*import Data.List 482 | minimum [1, 2, 3] 483 | maximum [1, 2, 3] 484 | `e zip-lists 485 | -- list of tuples: 486 | 487 | zip [1, 2, 3] ['a', 'b', 'c'] 488 | `e tuple 489 | (1, "hello", `=True) 490 | `e tuple-element-access 491 | (`+\(a, `+_, `+_) `+[->] a) (1, "hello", `=True) 492 | `e pair-element-access 493 | fst (12, "December") 494 | 495 | snd (12, "December") 496 | `e map-access 497 | `*import `*qualified Data.Map `*as M 498 | m M.! k 499 | `e map-size 500 | M.length m 501 | `e map-remove-element 502 | M.delete k m `c[returns new map] 503 | `e map-literal 504 | `c[none, use fromList:] 505 | M.fromList [('t', 1), ('f', 0)] 506 | `e is-key-present 507 | M.delete k m `c[returns new map] 508 | `e define-function 509 | average a b = (a + b) / 2.0 510 | `e invoke-function 511 | `c[4.5, as function application has highest precedence:] 512 | average 1 2 + 3 513 | 514 | `c[3.0:] 515 | average 1 (2 + 3) 516 | average 1 $ 2 + 3 517 | `e define-function-with-block-body 518 | 519 | `e named-parameters 520 | `e named-parameter-default-value 521 | `e piecewise-defined-function 522 | to_s Red = "red" 523 | to_s Green = "green" 524 | to_s Blue = "blue" 525 | `e recursive-function 526 | range a b = `*if a > b `*then [] `*else a : range (a+1) b 527 | `e mutually-recursive-functions 528 | 529 | `e lambda 530 | `+\x y `+[->] (x+y) / 2.0 531 | `e infix-operator-in-prefix-position 532 | ( * ) 3 4 533 | `e function-in-infix-position 534 | add x y = x + y 535 | 536 | 3 ``add`` 4 537 | `e currying 538 | plus2 = add 2 539 | plus2 = (+) 2 540 | `c[infix operators allow partial application by supplying one operand on either side:] 541 | half = (/ 2) 542 | twoOver = (2 /) 543 | `e composition 544 | f x = x + 2 545 | g x = x * 3 546 | 547 | (f . g) 4 548 | `e function-composition-operator 549 | double x = 2 * x 550 | quadruple x = double . double 551 | `e lazy-evaluation 552 | `c[lazy evaluation is default:] 553 | arg1 x y = x 554 | arg1 7 (error "bam!") 555 | `e strict-evaluation 556 | arg1 x y = seq y x 557 | arg1 7 (error "bam!") 558 | `e if 559 | `*if x > 0 560 | `*then putStrLn "pos" 561 | `*else return () 562 | `e control-structure-keywords 563 | `*if x > 0 564 | `*then putStrLn "pos" 565 | `*else `*if x < 0 566 | `*then putStrLn "neg" 567 | `*else putStrLn "zero" 568 | `e sequencing 569 | `*do 570 | putStrLn "one" 571 | putStrLn "two" 572 | putStrLn "three" 573 | `c[sugar for:] 574 | putStrLn "one" >> putStrLn "two" >> putStrLn "three" 575 | `e while 576 | 577 | `e for 578 | 579 | `e for-in-reverse 580 | 581 | `e list-iteration 582 | 583 | `e loop 584 | 585 | `e raise-error 586 | error "bam!" 587 | `e handle-error 588 | `*import System.IO.Error 589 | dangerous `+[::] IO () 590 | dangerous = error "bam!" 591 | 592 | handler `+[::] IOError `+[->] IO () 593 | handler e = putStrLn "Caught error!" 594 | 595 | dangerous ``catch`` handler 596 | `e type-of-exceptions 597 | IOError 598 | `e user-defined-exception 599 | 600 | `e standard-exceptions 601 | 602 | `e assert 603 | 604 | `e standard-file-handles 605 | `*import System.IO 606 | 607 | stdin, stdout, stderr `+[::] Handle 608 | `e read-line-from-stdin 609 | line `+[<-] getLine 610 | `e end-of-file-behavior 611 | when last data is returned, hIsEOF will return True. Reading after end-of-file throws an exception. 612 | `e chomp 613 | 614 | `e write-line-to-stdout 615 | putStrLn "lorem ipsum" 616 | `e printf 617 | `*import Text.Printf 618 | 619 | printf :: PrintfType r => String -> r 620 | `c[printf can be an IO action or a string, taking any number of format arguments, chosen by type-inference magic] 621 | `e open-file-for-reading 622 | `*import System.IO 623 | 624 | f `+[<-] openFile "/etc/hosts" ReadMode 625 | `e open-file-for-writing 626 | `*import System.IO 627 | 628 | f `+[<-] openFile "/tmp/test" WriteMode 629 | `e open-file-for-appending 630 | `*import System.IO 631 | 632 | f `+[<-] openFile "/tmp/err.log" AppendMode 633 | `e close-file 634 | `*import System.IO 635 | 636 | hClose f 637 | `e i-o-errors 638 | 639 | `e read-line 640 | line `+[<-] hGetLine f 641 | `e iterate-over-file-by-line 642 | readAndPrintLines h = `*do 643 | eof `+[<-] hIsEOF h 644 | `*if eof 645 | `*then return () 646 | `*else `*do 647 | line `+[<-] hGetLine h 648 | putStrLn line 649 | readAndPrintLines h 650 | 651 | main = `*do 652 | h `+[<-] openFile "/etc/passwd" ReadMode 653 | readAndPrintLines h 654 | 655 | `e read-file-into-array-of-strings 656 | 657 | `e read-file-into-string 658 | readFile "/etc/hosts" 659 | 660 | f `+[<-] openFile "/etc/hosts" ReadMode 661 | hGetContents f 662 | `e write-string 663 | hPutStr f "hello world" 664 | 665 | `e write-line 666 | s = "hello out\n" 667 | f = "/tmp/test-haskell" 668 | main = writeFile f s 669 | `e flush-file-handle 670 | hFlush f 671 | `e end-of-file-test 672 | 673 | `e get-and-set-file-handle-position 674 | 675 | `e file-exists-test-regular-test 676 | `*import System 677 | 678 | Directory.doesFileExist "/etc/hosts" 679 | 680 | `*import Control.Monad 681 | `*import System.Posix.Files 682 | 683 | liftM isRegularFile (getFileStatus "/etc/hosts") 684 | `e file-size 685 | `*import Control.Monad 686 | 687 | `*import System.Posix.Files 688 | 689 | 690 | liftM fileSize (getFileStatus "/etc/hosts") 691 | `e is-file-readable-writable-executable 692 | `*import Control.Monad 693 | 694 | liftM readable 695 | (getPermissions "/etc/hosts") 696 | liftM writable 697 | (getPermissions "/etc/hosts") 698 | liftM executable 699 | (getPermissions "/etc/hosts") 700 | `e set-file-permissions 701 | `*import System.Posix.Files 702 | 703 | setFileMode `=["/tmp/foo"] ownerModes 704 | setFileMode `=["/tmp/foo"] groupReadMode 705 | setFileMode `=["/tmp/foo"] groupExecuteMode 706 | setFileMode `=["/tmp/foo"] otherReadMode 707 | setFileMode `=["/tmp/foo"] otherExecuteMode 708 | `e copy-file-remove-file-rename-file 709 | `*import System.Directory 710 | 711 | copyFile `=["/tmp/foo"] `=["/tmp/bar"] 712 | removeFile `=["/tmp/foo"] 713 | renameFile `=["/tmp/bar"] `=["/tmp/foo"] 714 | `e create-symlink-symlink-test-readlink 715 | `*import System.Posix.Files 716 | 717 | createSymbolicLink "/etc/hosts" "/tmp/hosts" 718 | ?? 719 | readSymbolicLink "/tmp/hosts" 720 | `e generate-unused-file-name 721 | 722 | `e build-pathname 723 | `*import System.FilePath (()) 724 | 725 | `*let path = "/etc" "hosts" 726 | `e dirname-and-basename 727 | `*import System.FilePath 728 | 729 | takeFileName "/etc/hosts" 730 | takeDirectory "/etc/hosts" 731 | `e iterate-over-directory-by-file 732 | `*import System 733 | 734 | `c[returns IO [FilePath]] 735 | Directory.getDirectoryContents "/etc" 736 | `e make-directory 737 | `*import System.Directory 738 | 739 | createDirectoryIfMissing True 740 | "/tmp/foo/bar" 741 | `e remove-empty-directory 742 | `*import System.Directory 743 | 744 | removeDirectory "/tmp/foodir" 745 | `e remove-directory-and-contents 746 | `*import System.Directory 747 | 748 | removeDirectoryRecursive "/tmp/foodir" 749 | `e directory-test 750 | `*import System 751 | 752 | Directory.doesDirectoryExist "/tmp" 753 | `e system-temporary-file-directory 754 | 755 | `e command-line-arguments 756 | `*import System 757 | 758 | 759 | printArgs args = `*do 760 | `*if length args == 0 761 | `*then return () 762 | `*else `*do 763 | putStrLn (head args) 764 | printArgs (tail args) 765 | 766 | main = `*do 767 | a `+[<-] getArgs 768 | printArgs a 769 | `e program-name 770 | `*import System 771 | 772 | 773 | s `+[<-] getProgName 774 | `e getopt 775 | 776 | `e get-and-set-environment-variable 777 | `*import System.Posix.Env 778 | 779 | s `+[<-] getEnv "HOME" 780 | putEnv "PATH=/bin" 781 | `e get-pid-parent-pid 782 | `*import System.Posix.Process 783 | 784 | pid `+[<-] getProcessID 785 | ppid `+[<-] getParentProcessID 786 | `e get-user-id-and-name 787 | `*import System.Posix.User 788 | 789 | uid `+[<-] getRealUserID 790 | username `+[<-] getLoginName 791 | `e exit 792 | `*import System.Exit 793 | 794 | exitWith ExitSuccess 795 | 796 | `c[to return nonzero status:] 797 | exitWith (ExitFailure 1) 798 | `e set-signal-handler 799 | 800 | `e external-command 801 | `*import System.Cmd 802 | 803 | rawSystem "ls" ["-l", "/tmp"] 804 | `e escaped-external-command 805 | 806 | `e backticks 807 | 808 | `e namespace-example 809 | `c[Foo/Bar.hs] 810 | `*module Foo.Bar `*where 811 | data Baz = Baz 812 | say Baz = putStrLn "hello" 813 | 814 | `c[Main.hs] 815 | `*module Main `*where 816 | `*import Foo.Bar 817 | 818 | baz = Baz 819 | main = say baz 820 | 821 | `c[to compile and run] 822 | `$[ghc -c Foo/Bar.hs] 823 | `$[ghc Main.hs] 824 | `$[./Main] 825 | hello 826 | `e namespaces 827 | values, constructors, type variables, type constructors, type classes, modules 828 | `e file-name-restrictions 829 | module Foo.Bar must be in Foo/Bar.hs 830 | `e namespace 831 | `*import Data.Bytestring 832 | `e namespace-creation 833 | 834 | `e namespace-alias 835 | `*import `*qualified Data.Bytestring `*as B 836 | `e namespace-separator 837 | . 838 | `e subnamespace 839 | 840 | `e package-manager-setup 841 | 842 | `e package-manager-search-install-list-installed 843 | `$[cabal list parsec] 844 | `$[cabal install parsec] 845 | `$[cabal list --installed] 846 | `e compile-app-using-package 847 | 848 | `e type-synonym 849 | `*type Name = String 850 | `e sum-type 851 | `*data Color = Red | Green | Blue `*deriving (Eq, Ord, Show) 852 | col = Red 853 | 854 | print col `c[Red] 855 | col < Green `c[True] 856 | `e tuple-product-type-with-one-field 857 | `*data SpecialIntType = SpecialInt `.Integer 858 | n = SpecialInt 7 859 | 860 | `*newtype SpecialIntType = SpecialInt { runSpecialInt :: `.Integer } 861 | n = SpecialInt 7 862 | `e tuple-product-type-with-two-fields 863 | `*data IntPairType = IntPair Integer Integer 864 | 865 | p = IntPair 7 11 866 | `e record-product-type 867 | `*data CustomerType = Customer { 868 | customerId `+[::] Integer, 869 | name `+[::] String, 870 | address `+[::] String 871 | } 872 | `e record-product-type-literal 873 | Customer { 874 | customerId=7, 875 | name="John", 876 | address="Topeka, KS" 877 | } 878 | `e generic-type 879 | `*data TwosomeType a b = Twosome a b 880 | 881 | p = Twosome ("pi", 3.14) 882 | `e recursive-type 883 | `*data BinaryTree = Leaf Integer | Tree BinaryTree BinaryTree 884 | `e pattern-match-sum-type 885 | c = Red 886 | 887 | `*case c `*of Red `+[->] "red" 888 | Green `+[->] "green" 889 | Blue `+[->] "blue" 890 | `e pattern-match-product-type 891 | 892 | `e pattern-match-guard 893 | none, use `*if or piecewise function definition 894 | `e pattern-match-catchall 895 | c = Green 896 | `*case c `*of Red `+[->] "red"; `+_ `+[->] "not red" 897 | `e define-class 898 | 899 | `e create-object 900 | 901 | `e invoke-method 902 | 903 | `e field-access 904 | 905 | `e overload-function 906 | 907 | `e inheritance 908 | 909 | `e invoke-repl 910 | $ ghci 911 | `e repl-limitations 912 | Must use `*let to define values and functions; when defining functions with multiple equations the equations must be separated by semicolons; the clauses of case/of statements must be separated by semicolons; it is not possible to define data types. 913 | `e repl-last-value 914 | it 915 | `e help 916 | :? 917 | `e quit 918 | 919 | `e inspect-type 920 | `*let a = 3 921 | :type a 922 | `e inspect-namespace 923 | 924 | `e load-source-file 925 | :edit hello.hs 926 | :load hello 927 | `e load-package 928 | 929 | `e search-path 930 | 931 | `e set-search-path-on-command-line 932 | 933 | -------------------------------------------------------------------------------- /javascript.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | ECMAScript 5 3 | `e show-version 4 | `$[node --version] 5 | `e interpreter 6 | `$[node foo.js] 7 | `e repl 8 | `$[node] 9 | `e command-line-program 10 | `$[node -e 'var sys = require("sys"); 11 | sys.puts("hi world!");'] 12 | `e block-delimiters 13 | {} 14 | `e statement-terminator 15 | ; or newline 16 | 17 | newline not separator inside (), [], {}, "", '', or after binary operator 18 | 19 | newline sometimes not separator when following line would not parse as a valid statement 20 | `e are-expressions-statements 21 | yes 22 | `e end-of-line-comment 23 | // comment 24 | `e multiple-line-comment 25 | /* comment 26 | another comment */ 27 | `e local-variable 28 | `*var x = 1; 29 | `e global-variable 30 | `c[assign without using var] 31 | 32 | g = 1; 33 | `*function incr_global () { g++; } 34 | `e assignment 35 | x = 1; 36 | `e parallel-assignment 37 | `e swap 38 | `*var tmp = x; 39 | x = y; 40 | y = tmp; 41 | `e null 42 | `=null 43 | `e null-test 44 | `*typeof v === `=["undefined"] && v === `=[null] 45 | `e uninitialized-local-variable 46 | `=undefined 47 | `e uninitialized-global-variable 48 | `=undefined 49 | `e conditional-expression 50 | x > 0 ? x : -x 51 | `e true-and-false 52 | `=true `=false 53 | `e falsehoods 54 | `=false `=null `=undefined "" 0 `=NaN 55 | `e logical-operators 56 | && || ! 57 | `e relational-expression 58 | x > 3 59 | `e relational-operators 60 | === !== < > >= <= 61 | `c[perform type coercion:] 62 | == != 63 | `e min-and-max 64 | Math.min(1, 2, 3) 65 | Math.max(1, 2, 3) 66 | 67 | Math.min.apply(Math, [1, 2, 3]) 68 | Math.max.apply(Math, [1, 2, 3]) 69 | `e arithmetic-expression 70 | 1 + 3 71 | `e arithmetic-operators 72 | + - * / `c[none] % 73 | `e integer-division 74 | Math.floor(x / y) 75 | `e integer-division-by-zero 76 | returns assignable value `=Infinity, `=NaN, or -`=Infinity depending upon whether dividend is positive, zero, or negative. 77 | 78 | There are literals for `=Infinity and `=NaN. 79 | `e float-division 80 | x / y 81 | `e float-division-by-zero 82 | `c[same behavior as for integers] 83 | `e power 84 | Math.pow(2, 32) 85 | `e sqrt 86 | Math.sqrt(2) 87 | `e sqrt-1 88 | `=NaN 89 | `e transcendental-functions 90 | Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2 91 | `e transcendental-constants 92 | Math.PI 93 | Math.E 94 | `e float-truncation 95 | `c[none] 96 | 97 | Math.round(3.1) 98 | 99 | Math.floor(3.1) 100 | 101 | Math.ceil(3.1) 102 | `e absolute-value-and-signum 103 | Math.abs(-3) 104 | `e integer-overflow 105 | `c[all numbers are floats] 106 | `e float-overflow 107 | `=Infinity 108 | `e random-number-uniform-integer-uniform-float-normal-float 109 | Math.floor(Math.random() * 100) 110 | 111 | Math.random() 112 | `c[none] 113 | `e bit-operators 114 | << >> & | ^ ~ 115 | `e binary-octal-and-hex-literals 116 | `c[none] 117 | 052 118 | 0x2a 119 | `e radix 120 | `e string-literal 121 | `=["don't say \"no\""] 122 | `=['don\'t say "no"'] 123 | `e newline-in-literal 124 | yes 125 | `e literal-escapes 126 | `c[single and double quotes:] 127 | `%[\b \f \n \r \t \v \uhhhh \xhh \" \' \\] 128 | `e concatenate-strings 129 | s = `=["Hello, "] + `=["World!"]; 130 | `e split 131 | `=["do re mi"].split(`=[" "]) 132 | `e join 133 | [`=["do"], `=["re"], `=["mi"]].join(`=[" "]) 134 | `e translate-case 135 | `=["lorem"].toUpperCase() 136 | `=["LOREM"].toLowerCase() 137 | `c[none] 138 | `e trim 139 | `=[" lorem "].trim() 140 | `c[some browsers:] 141 | `=[" lorem"].trimLeft() 142 | `=["lorem "].trimRight() 143 | `e pad 144 | `e string-to-number 145 | 7 + `.parseInt("12", 10) 146 | 147 | 73.9 + `.parseFloat(".037") 148 | `e number-to-string 149 | `=["value: "] + 8 150 | `e string-length 151 | `=["lorem"].length 152 | `e index-of-substring 153 | `=["lorem ipsum"].indexOf(`=["ipsum"]) 154 | `e extract-substring 155 | `=["lorem ipsum"].substr(6, 5) 156 | `=["lorem ipsum"].substring(6, 11) 157 | `e extract-character 158 | `=["lorem ipsum"].charAt(6) 159 | `=["lorem ipsum"].charCodeAt(6) 160 | `e test-character 161 | `c[use regexes, somehow] 162 | `=[/^[a-zA-Z]$/].test(`=['c']) 163 | `=[/^\d$/].test(`=['c']) 164 | `=[/^\s$/].test(`=['c']) 165 | `=[/^[A-Z]$/].test(`=['c']) 166 | `=[/^[a-z]$/].test(`=['c']) 167 | `c[for speed, use charCode comparisons] 168 | `e chr-and-ord 169 | String.fromCharCode(65) 170 | `=["A"].charCodeAt(0) 171 | `e character-class-abbreviations-and-anchors 172 | char class abbrevs: 173 | 174 | . \d \D \s \S \w \W 175 | 176 | anchors: ^ $ \b \B 177 | `e match-test 178 | `*if (s.match(`=[/1999/])) { 179 | alert("party!"); 180 | } 181 | `e case-insensitive-match-test 182 | "Lorem".match(`=[/lorem/i]) 183 | `e modifiers 184 | g i m 185 | `e substitution 186 | s = "do re mi mi mi"; 187 | s.replace(`=[/mi/g], "ma"); 188 | `e group-capture 189 | rx = `=[/^(\d{4})-(\d{2})-(\d{2})$/]; 190 | m = rx.exec('2009-06-03'); 191 | yr = m[1]; 192 | mo = m[2]; 193 | dy = m[3]; 194 | `e backreference-in-match-and-substitution 195 | `=[/(w+) \1/].exec("do do") 196 | "do re".replace(`=[/(\w+) (\w+)/], '$2 $1') 197 | `e current-date-time 198 | `*var t = `*new Date(); 199 | `e to-unix-epoch-from-unix-epoch 200 | Math.round(t.getTime() / 1000) 201 | `*var epoch = 1315716177; 202 | `*var t2 = new Date(epoch * 1000); 203 | `e parse-date-w-o-format 204 | `*var t = new Date("July 7, 1999"); 205 | `e date-parts 206 | t.getFullYear() 207 | t.getMonth() + 1 208 | t.getDate() `c[getDay(] is day of week) 209 | `e time-parts 210 | t.getHours() 211 | t.getMinutes() 212 | t.getSeconds() 213 | `e build-date-time-from-parts 214 | `*var yr = 1999; 215 | `*var mo = 9; 216 | `*var dy = 10; 217 | `*var hr = 23; 218 | `*var mi = 30; 219 | `*var ss = 0; 220 | `*var t = new Date(yr,mo-1,dy,hr,mi,ss); 221 | `e list-name 222 | array 223 | `e list-literal 224 | a = [1, 2, 3, 4] 225 | `e list-size 226 | a.length 227 | `e empty-list 228 | [] 229 | `e empty-test 230 | a.length === 0 231 | `e head 232 | a[0] 233 | `e list-lookup 234 | a[0] 235 | `e list-update 236 | a[0] = "lorem" 237 | `e list-out-of-bounds 238 | returns `=undefined 239 | `e index-of-element 240 | [6, 7, 7, 8].indexOf(7) 241 | [6, 7, 7, 8].lastIndexOf(7) 242 | `c[returns -1 if not found] 243 | `e slice 244 | ["a", "b", "c", "d"].slice(1,3) 245 | `e drop 246 | ["a", "b", "c", "d"].slice(1) 247 | `e concatenate 248 | a = [1, 2, 3].concat([4, 5, 6]); 249 | `e manipulate-back 250 | a = [6, 7, 8]; 251 | a.push(9); 252 | i = a.pop(); 253 | `e manipulate-front 254 | a = [6, 7, 8]; 255 | a.unshift(5); 256 | i = a.shift(); 257 | `e iterate-over-elements 258 | `*var len = a.length; 259 | `*for (`*var i = 0; i < len; i++ ) { 260 | `.alert(a[i]); 261 | } 262 | `e reverse 263 | `*var a = [1, 2, 3]; 264 | a.reverse(); 265 | `e sort 266 | `*var a = [3, 1, 4, 2]; 267 | a.sort(); 268 | `e map 269 | `c[callback gets 3 args: value, index, array] 270 | a.map(`*function(x) { `*return x * x }) 271 | `e filter 272 | a.filter(`*function(x) { `*return x > 1 }) 273 | `e fold-from-left 274 | a.reduce(`*function(m, o) { 275 | `*return m + o; 276 | }, 0) 277 | `e universal-test 278 | `*var a = [1, 2, 3, 4]; 279 | `*var even = `*function(x) { 280 | `*return x % 2 == 0; 281 | }; 282 | a.every(even) 283 | `e existential-test 284 | a.some(even) 285 | `e map-literal 286 | d = { "t":1, "f":0 }; 287 | `c[keys do not need to be quoted if they are a legal JavaScript variable name and not a reserved word] 288 | `e map-size 289 | `*var size = 0; 290 | `*for (`*var k in d) { 291 | `*if (d.hasOwnProperty(k)) size++; 292 | } 293 | `e map-lookup 294 | d.t 295 | d["t"] 296 | `e map-access 297 | d["t"] = 2; 298 | d.t = 2; 299 | `e map-out-of-bounds 300 | returns `=undefined 301 | `e is-key-present 302 | d.hasOwnProperty("t"); 303 | `e map-remove-element 304 | `*delete d["t"]; 305 | `*delete d.t; 306 | `e iteration 307 | `*for (`*var k in d) { 308 | `c[use k or d[k]] 309 | } 310 | `e declare-function 311 | `*function add(x, y) { 312 | return x+y; 313 | } 314 | `e invoke-function 315 | add(1, 2) 316 | `e missing-argument-behavior 317 | `=undefined 318 | `e extra-arguments 319 | available in arguments 320 | `e default-value 321 | `e variable-number-of-arguments 322 | args in arguments[0], arguments[1], … with number of args in arguments.length 323 | `e return-value 324 | return arg or undefined. If invoked with new and return value not an object, returns this 325 | `e multiple-return-values 326 | none 327 | `e lambda 328 | sqr = `*function(x) { return x*x; } 329 | `e lambda-invocation 330 | sqr(2) 331 | `e default-scope 332 | global unless declared with `*var 333 | `e nested-function-visibility 334 | not visible outside containing function 335 | `e if 336 | `*if (0 == n) { 337 | `.alert("no hits"); 338 | } `*else `*if (1 == n) { 339 | `.alert("1 hit"); 340 | } `*else { 341 | `.alert(n + " hits"); 342 | } 343 | `e while 344 | `*while ( i < 100 ) { 345 | i += 1; 346 | } 347 | `e break 348 | `*break 349 | `e continue 350 | `*continue 351 | `e break-continue-redo 352 | `*break `*continue 353 | `e c-style-for 354 | `*for (`*var i=0; i<10; i++) { 355 | `.alert(i); 356 | } 357 | `e raise-exception 358 | `*throw "bad arg"; 359 | `e catch-exception 360 | `*try { 361 | risky(); 362 | } `*catch (e) { 363 | `.alert("risky failed"); 364 | } 365 | `e finally 366 | acquire_resource(); 367 | `*try { 368 | risky(); 369 | } `*finally { 370 | release_resource(); 371 | } 372 | `e uncaught-exception-behavior 373 | error to console; script terminates. Other scripts in page will execute 374 | 375 | `e read-line-from-stdin 376 | js: 377 | `*var line = readline(); 378 | `e write-line-to-stdout 379 | `*var sys = require('sys'); 380 | 381 | sys.puts("Hello, World!"); 382 | `e open-file-for-reading 383 | `*var fs = require('fs'); 384 | 385 | f = fs.openSync("/tmp/foo", "r"); 386 | `e open-file-for-writing 387 | `*var fs = require('fs'); 388 | 389 | f = fs.openSync("/tmp/foo", "w"); 390 | `e close-file 391 | fs.closeSync(f); 392 | `e read-line 393 | 394 | `e iterate-over-file-by-line 395 | `*var fs = require('fs'); 396 | 397 | 398 | `*var file = fs.readFileSync("/etc/hosts").toString(); 399 | 400 | file.split("\n").forEach(`*function (s) { 401 | use s 402 | 403 | }); 404 | `e chomp 405 | 406 | `e read-file 407 | `*var fs = require('fs'); 408 | 409 | 410 | fs.readFileSync("/tmp/foo", "utf8"); 411 | `e write-to-file 412 | fs.writeSync(f, "lorem ipsum"); 413 | `e flush-file-handle 414 | none 415 | `e file-exists-test-regular-test 416 | `*var path = require('path'); 417 | 418 | 419 | path.existsSync("/etc/hosts"); 420 | `e file-size 421 | 422 | `e is-file-readable-writable-executable 423 | 424 | `e copy-file-remove-file-rename-file 425 | `*var fs = require('fs'); 426 | 427 | ?? 428 | 429 | fs.unlink("/tmp/foo"); 430 | 431 | fs.rename("/tmp/bar", "/tmp/foo"); 432 | `e set-file-permissions 433 | `*var fs = require('fs'); 434 | 435 | 436 | fs.chmod("/tmp/foo", 0755); 437 | `e temporary-file 438 | 439 | `e build-pathname 440 | `*var path = require('path'); 441 | 442 | 443 | path.join("/etc", "hosts"); 444 | `e dirname-and-basename 445 | `*var path = require('path'); 446 | 447 | 448 | path.dirname("/etc/hosts"); 449 | 450 | path.basename("/etc/hosts"); 451 | `e iterate-over-directory-by-file 452 | `*var fs = require('fs'); 453 | 454 | `*var sys = require('sys'); 455 | 456 | 457 | `*var a = fs.readdirSync("/etc"); 458 | 459 | `*for (`*var i=0; i 514 | 515 | <`*script> 516 | `.alert(add(3,7)); 517 | 518 | `e library-path 519 | `c[node.js, not available in repl:] 520 | 521 | require.paths 522 | `e library-path-environment-variable 523 | 524 | `e declare-namespace 525 | 526 | `e namespace-separator 527 | 528 | `e list-installed-packaged-install-a-package 529 | `$[npm ls] 530 | 531 | `$[npm install tmp] 532 | `e define-class 533 | 534 | `e create-object 535 | 536 | `e create-blank-object 537 | `*var o = `*new Object(); or 538 | 539 | `*var o = {}; 540 | `e set-attribute 541 | o.score = 21; 542 | `e get-attribute 543 | `*if (o.score == 21) { 544 | `.alert("Blackjack!"); 545 | } 546 | `e define-method 547 | o.doubleScore = `*function() { 548 | `*return this.score * 2; 549 | }; 550 | `e invoke-method 551 | `.alert("Answer: " + o.doubleScore()); 552 | `e clone-object 553 | `*var o2 = Object.create(o); 554 | `e object-literal 555 | `*var o = { 556 | score: 21, 557 | doubleScore: `*function() { 558 | `*return this.score * 2; 559 | } 560 | }; 561 | `e inspect-type 562 | typeof o 563 | `e has-method 564 | typeof o.foo == 'function' 565 | `e message-passing 566 | o["foo"](1,1) 567 | `e eval 568 | x = `.eval("1 + 1"); 569 | `e inspect-methods 570 | 571 | `e inspect-attributes 572 | 573 | -------------------------------------------------------------------------------- /lua.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | 5.1 3 | `e show-version 4 | `$[lua -v] 5 | `e interpreter 6 | `$[lua foo.lua] 7 | `e repl 8 | `$[lua] 9 | `e command-line-program 10 | `$[lua -e 'print("hi world!")'] 11 | `e block-delimiters 12 | `*do `*end 13 | `e statement-terminator 14 | newline or ; 15 | 16 | newline not separator inside {}, (), or after binary operator. 17 | 18 | newline can be put in "" or '' if preceded by backslash 19 | `e are-expressions-statements 20 | no 21 | `e end-of-line-comment 22 | -- comment 23 | `e multiple-line-comment 24 | --[[ 25 | commented out 26 | also commented out 27 | ]] 28 | `e local-variable 29 | `*local x = 1 30 | `e global-variable 31 | `c[assign without using local] 32 | g = 1 33 | 34 | `*function incr_global() 35 | g = g + 1 36 | `*end 37 | `e assignment 38 | x = 1 39 | `e parallel-assignment 40 | x, y, z = 1, 2, 3 41 | 42 | `c[3 is discarded:] 43 | x, y = 1, 2, 3 44 | 45 | `c[z is set to nil:] 46 | x, y, z = 1, 2 47 | `e swap 48 | x, y = y, x 49 | `e null 50 | `=nil 51 | `e null-test 52 | v == `=nil 53 | `e uninitialized-local-variable 54 | `=nil 55 | `e uninitialized-global-variable 56 | `=nil 57 | `e conditional-expression 58 | none 59 | `e true-and-false 60 | true false 61 | `e falsehoods 62 | false `=nil 63 | `e logical-operators 64 | `*and `*or `*not 65 | `e relational-expression 66 | x > 3 67 | `e relational-operators 68 | == ~= < > >= <= 69 | `e min-and-max 70 | math.min(1, 2, 3) 71 | 72 | math.max(1, 2, 3) 73 | 74 | 75 | math.min(unpack({1 ,2 ,3})) 76 | 77 | math.max(unpack({1, 2, 3})) 78 | `e arithmetic-expression 79 | 1 + 3 80 | `e arithmetic-operators 81 | + - * / `c[none] % ^ 82 | `e integer-division 83 | math.floor(x / y) 84 | `e integer-division-by-zero 85 | returns assignable value inf, nan, or -inf depending upon whether dividend is positive, zero, or negative. 86 | 87 | 88 | There are no literals for any of these values. 89 | `e float-division 90 | x / y 91 | `e float-division-by-zero 92 | same behavior as for integers 93 | `e power 94 | 2 ^ 32 95 | 96 | math.pow(2, 32) 97 | `e sqrt 98 | math.sqrt(2) 99 | `e sqrt-1 100 | nan 101 | `e transcendental-functions 102 | math.exp math.log math.sin math.cos math.tan math.asin math.acos math.atan math.atan2 103 | `e transcendental-constants 104 | math.pi 105 | 106 | math.exp(1) 107 | `e float-truncation 108 | none 109 | none 110 | 111 | math.floor(3.1) 112 | 113 | math.ceil(3.1) 114 | `e absolute-value-and-signum 115 | math.abs(-3) 116 | `e integer-overflow 117 | all numbers are floats 118 | `e float-overflow 119 | inf 120 | `e random-number-uniform-integer-uniform-float-normal-float 121 | math.random(100) - 1 122 | 123 | math.random() 124 | none 125 | `e random-seed 126 | math.randomseed(17) 127 | `e bit-operators 128 | none 129 | `e string-literal 130 | "don't say \"no\"" 131 | 132 | 'don\'t say "no"' 133 | `e newline-in-literal 134 | yes, if preceded by backslash 135 | `e literal-escapes 136 | single and double quotes: 137 | 138 | \a \b \f \n \r \t \v \" \' \\ \ddd 139 | `e variable-interpolation 140 | none 141 | `e expression-interpolation 142 | none 143 | `e concatenate-strings 144 | s = "Hello, " .. "World!" 145 | `e split 146 | none 147 | `e join 148 | table.concat({"do","re","mi"}, " ") 149 | `e format 150 | string.format("lorem %s %d %.2f", 151 | "ipsum", 13, 3.7) 152 | `e translate-case 153 | string.upper("lorem") 154 | 155 | string.lower("LOREM") 156 | none 157 | `e pad 158 | none 159 | `e string-to-number 160 | 7 + tonumber("12") 161 | 162 | 73.9 + tonumber(".037") 163 | arithmetic operators attempt numeric conversion of string operands 164 | `e number-to-string 165 | "value: " .. 8 166 | `e string-length 167 | string.len("lorem") 168 | `e index-of-substring 169 | string.find("lorem ipsum", "ipsum") 170 | `e extract-substring 171 | string.sub("lorem ipsum", 7, 11) 172 | `e chr-and-ord 173 | string.char(65) 174 | 175 | string.byte("A") 176 | `e character-class-abbreviations 177 | `%[. %a %c %d %l %p %s %u %w %x %z] 178 | `e anchors 179 | `%[^ $] 180 | `e match-test 181 | `*if string.match(s, "1999") `*then 182 | `.print("party!") 183 | `*end 184 | `e case-insensitive-match-test 185 | none 186 | `e modifiers 187 | none 188 | `e substitution 189 | s = "do re mi mi mi" 190 | 191 | s = string.gsub(s, "mi", "ma") 192 | `e group-capture 193 | s = "2010-06-03" 194 | 195 | rx = "(%d+)-(%d+)-(%d+)" 196 | 197 | yr, mo, dy = string.match(s, rx) 198 | `e backreference-in-match-and-substitution 199 | string.match("do do", "(%w+) %1") 200 | 201 | 202 | rx = "(%w+) (%w+)" 203 | 204 | string.gsub("do re", rx, "%2 %1") 205 | `e current-date-time 206 | t = os.time() 207 | `e to-unix-epoch-from-unix-epoch 208 | t 209 | 210 | t2 = 1315716177 211 | `e strftime 212 | os.date("%Y-%m-%d %H:%M:%S", t) 213 | `e strptime 214 | none 215 | `e parse-date-w-o-format 216 | none 217 | `e date-parts 218 | none 219 | `e time-parts 220 | none 221 | `e build-date-time-from-parts 222 | none 223 | `e sleep 224 | none 225 | `e list-literal 226 | a = { 1, 2, 3, 4 } 227 | `e list-size 228 | -- not well-defined if array 229 | -- contains nil values: 230 | 231 | # a 232 | `e list-lookup 233 | a[1] 234 | `e list-update 235 | a[1] = "lorem" 236 | `e list-out-of-bounds 237 | returns `=nil 238 | `e index-of-element 239 | none; use for and ipairs 240 | `e slice 241 | none 242 | `e drop 243 | none 244 | `e concatenate 245 | none 246 | `e list-replicate 247 | none 248 | `e manipulate-back 249 | a = {6, 7, 8} 250 | 251 | table.insert(a, 9) 252 | 253 | i = table.remove(a) 254 | `e manipulate-front 255 | a = {6, 7, 8} 256 | 257 | table.insert(a, 1, 5) 258 | 259 | i = table.remove(a, 1) 260 | `e iterate-over-elements 261 | `*for k,v `*in ipairs(a) `*do 262 | `.print(v) 263 | `*end 264 | `e reverse 265 | none 266 | `e sort 267 | a = {3, 1, 4, 2} 268 | 269 | table.sort(a) 270 | `e dedupe 271 | none 272 | `e membership 273 | none 274 | `e intersection 275 | none 276 | `e union 277 | none 278 | `e relative-complement-symmetric-difference 279 | none 280 | `e map 281 | none 282 | `e filter 283 | none 284 | `e fold-from-left 285 | none 286 | `e shuffle-and-sample 287 | none 288 | `e zip 289 | none 290 | `e map-literal 291 | d = { t=1, f=0 } 292 | `e map-size 293 | size = 0 294 | `*for k, v `*in pairs(d) `*do 295 | size = size + 1 296 | `*end 297 | `e map-lookup 298 | d.t 299 | 300 | d["t"] 301 | `e map-update 302 | d["t"] = 2 303 | 304 | d.t = 2 305 | `e map-out-of-bounds 306 | returns `=nil 307 | `e is-key-present 308 | d["t"] ~= `=nil 309 | `e delete-entry 310 | d.t = `=nil 311 | 312 | d["t"] = `=nil 313 | `e iteration 314 | `*for k,v `*in pairs(d) `*do 315 | use k or v 316 | `*end 317 | `e declare-function 318 | `*function add(x, y) 319 | `*return x + y 320 | `*end 321 | `e invoke-function 322 | add(1, 2) 323 | `e missing-argument-behavior 324 | `=nil 325 | `e extra-arguments 326 | ignored 327 | `e default-value 328 | none 329 | `e variable-number-of-arguments 330 | declare function with ellipsis: 331 | `*function foo(...) 332 | `*local arg = {...} 333 | `e return-value 334 | `*return arg 335 | or `=nil 336 | `e multiple-return-values 337 | `*function roots(x) 338 | r = math.sqrt(x) 339 | `*return r, -r 340 | `*end 341 | 342 | r1,r2 = roots(4) 343 | `e lambda 344 | sqr = `*function(x) `*return x*x `*end 345 | `e lambda-invocation 346 | sqr(2) 347 | `e default-scope 348 | global unless declared with `*local 349 | `e nested-function-visibility 350 | visible outside containing function 351 | `e if 352 | `*if n == 0 `*then 353 | `.print("no hits") 354 | `*elseif n == 1 `*then 355 | `.print("one hit") 356 | `*else 357 | `.print(n .. " hits") 358 | `*end 359 | `e while 360 | `*while i < 100 `*do 361 | i = i + 1 362 | `*end 363 | `e break-continue-redo 364 | break none 365 | `e for 366 | `*for i = 0, 9 `*do 367 | `.print(i) 368 | `*end 369 | `e raise-exception 370 | error "bad arg" 371 | `e catch-exception 372 | `*if `*not pcall(risky) `*then 373 | `.print "risky failed" 374 | `*end 375 | `e finally 376 | none 377 | `e uncaught-exception-behavior 378 | stderr and exit 379 | `e generator 380 | crt = coroutine.create( 381 | `*function (n) 382 | `*while (true) `*do 383 | coroutine.yield(n % 2) 384 | n = n + 1 385 | `*end 386 | `*end 387 | ) 388 | 389 | status, retval = 390 | coroutine.resume(crt, 1) 391 | `*if status `*then 392 | `.print("parity: " .. retval) 393 | `*else 394 | `.print("couldn't resume crt") 395 | `*end 396 | 397 | 398 | _, retval = coroutine.resume(crt) 399 | 400 | `.print("parity: " .. retval) 401 | `e standard-file-handles 402 | io.stdin 403 | 404 | io.stdout 405 | 406 | io.stderr 407 | `e read-line-from-stdin 408 | line = io.stdin:read() 409 | `e write-line-to-stdout 410 | `.print "Hello, World!" 411 | `e open-file-for-reading 412 | f = io.open("/tmp/foo") 413 | `e open-file-for-writing 414 | f = io.open("/tmp/foo", "w") 415 | `e close-file 416 | f:close() 417 | `e read-line 418 | f:read() 419 | `e iterate-over-file-by-line 420 | `*for s `*in f:lines() `*do 421 | use s 422 | `*end 423 | `e chomp 424 | none, read() and lines() remove trailing newlines 425 | `e read-file 426 | f:read("*a") 427 | `e write-to-file 428 | f:write("lorem ipsum") 429 | `e flush-file-handle 430 | f:flush() 431 | `e file-exists-test-regular-test 432 | none 433 | `e file-size 434 | 435 | `e is-file-readable-writable-executable 436 | 437 | `e copy-file-remove-file-rename-file 438 | none 439 | `e set-file-permissions 440 | none 441 | `e temporary-file 442 | f = io.tmpfile() 443 | 444 | f:write("lorem ipsum\n") 445 | 446 | f:close() 447 | ?? 448 | `e build-pathname 449 | 450 | `e dirname-and-basename 451 | 452 | `e iterate-over-directory-by-file 453 | 454 | `e make-directory 455 | 456 | `e remove-empty-directory 457 | 458 | `e remove-directory-and-contents 459 | 460 | `e directory-test 461 | 462 | `e command-line-arguments 463 | # arg 464 | 465 | arg[0] 466 | 467 | arg[1] 468 | … 469 | `e environment-variable 470 | os.getenv("HOME") 471 | `e exit 472 | os.exit(0) 473 | `e external-command 474 | os.execute("ls") 475 | `e backticks 476 | f = io.popen("ls") 477 | 478 | s = f:read("*a") 479 | `e library 480 | $ cat foo.lua 481 | 482 | `*function add(x, y) `*return x+y `*end 483 | `e import-library 484 | require 'foo' 485 | 486 | add(3,7) 487 | `e library-path 488 | package.path 489 | `e library-path-environment-variable 490 | LUA_PATH 491 | `e declare-namespace 492 | module 493 | `e namespace-separator 494 | . 495 | `e list-installed-packaged-install-a-package 496 | 497 | `e define-class 498 | 499 | `e create-object 500 | 501 | `e create-blank-object 502 | o = {} 503 | `e set-attribute 504 | o.score = 21 505 | `e get-attribute 506 | `*if o.score == 21 `*then 507 | `.print("Blackjack!") 508 | `*end 509 | `e define-method 510 | `*function o.doubleScore(self) 511 | `*return 2 * self.score 512 | `*end 513 | `e invoke-method 514 | `.print("Answer: " .. o:doubleScore()) 515 | `e clone-object 516 | 517 | `e object-literal 518 | o = { 519 | score=21, 520 | doubleScore=`*function(self) 521 | `*return 2*self.score 522 | `*end 523 | } 524 | `e inspect-type 525 | type(o) 526 | `e has-method 527 | 528 | `e message-passing 529 | 530 | `e eval 531 | assert(loadstring("x = 1+1"))() 532 | `e inspect-methods 533 | 534 | `e inspect-attributes 535 | 536 | -------------------------------------------------------------------------------- /morph.css: -------------------------------------------------------------------------------- 1 | @import url(http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); 2 | body, h1 { 3 | margin: 0; 4 | padding: 0; 5 | } 6 | #wrapper { 7 | padding: 1em 1em 7em 1em; 8 | } 9 | #cc { color: #777; } 10 | #toc { 11 | position: fixed; 12 | bottom: 0; 13 | margin: 0; 14 | padding: 1em; 15 | width: 100%; 16 | background-color: #eef; 17 | background-color: rgba(238, 238, 255, 0.8); 18 | z-index: 1; 19 | } 20 | #toc a { color: #00c; text-decoration: none; } 21 | #toc a:hover { color: #06c; text-decoration: underline overline; } 22 | #toc a.ts { color: #099; text-decoration: underline overline; text-shadow: #0ff 0 0 0.1em; } 23 | #morpher { 24 | background-color: #eff; 25 | margin: 1em 0; 26 | } 27 | table { border-collapse: collapse; } 28 | th { 29 | font-family: sans-serif; 30 | border: 1px solid #bbb; 31 | padding: 0.3em 0.7em; 32 | background-color: #eee; 33 | background: linear-gradient(to bottom, #fff, #eee); 34 | } 35 | th.section-header { 36 | text-align: left; 37 | background-color: #dde; 38 | background: linear-gradient(to bottom, #eef, #ddf); 39 | } 40 | td.cont { color: #000; border: 1px solid #bbb; padding: 0.3em 0.7em; font-size: 12pt; font-family: "Ubuntu Mono", monospace; min-width: 10em; } 41 | td.empty { background-color: #eee; border: 1px dotted #bbb; } 42 | td.desc { color: #000; border: 1px solid #bbb; padding: 0.3em 0.7em 0.3em 1.0em; font-family: sans-serif; background-color: #eee; background: linear-gradient(135deg, #fff, #eee); color: black; } 43 | .pd { position: relative; } 44 | a.perm { position: absolute; left: -0.7em; text-decoration: none; color: #bbb; } 45 | a.perm:hover { color: blue; } 46 | .key { color: #909; font-weight: bold; } 47 | .op { color: #c60; } 48 | .val { color: #00c; } 49 | .sval { color: #03f; } 50 | .builtin { color: #099; } 51 | .note { color: #777; font-style: italic; } 52 | .empty { background-color: #eee; } 53 | .error { display: block; padding: 0 0.2em; border-radius: 0.2em; color: #900; background-color: #fdd; } 54 | .cli:before { content: "$ "; color: #ccc; } 55 | .preproc { color: #090; } 56 | -------------------------------------------------------------------------------- /morph.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleContexts #-} 2 | import qualified Data.Map as M 3 | import qualified Data.Set as S 4 | import System.IO 5 | import Control.Applicative ((<$>)) 6 | import Control.Monad 7 | import Data.Char 8 | import Data.Function 9 | import Data.List 10 | import Data.Monoid (mconcat) 11 | import System.Environment 12 | import Text.Parsec 13 | 14 | -- utility HTML-making functions 15 | 16 | makeSpanTag :: String -> String -> String 17 | makeSpanTag cls cont = 18 | "" ++ cont ++ "" 19 | 20 | -- parsing 21 | type CharParser = Parsec String () 22 | 23 | isId :: Char -> Bool 24 | isId c = isAlphaNum c || c == '_' 25 | idChar :: CharParser Char 26 | idChar = satisfy isId 27 | 28 | isKeyChar :: Char -> Bool 29 | isKeyChar c = isAlphaNum c || c == '-' 30 | keyChar :: CharParser Char 31 | keyChar = satisfy isKeyChar 32 | 33 | toKey :: String -> String 34 | toKey = intercalate "-" . filter (isAlphaNum . head) . groupBy ((==) `on` isAlphaNum) 35 | 36 | bqAtom :: CharParser String 37 | bqAtom = bqSpecial <|> plainAtom 38 | 39 | plainAtom :: CharParser String 40 | plainAtom = htmlEscaped <|> htmlNewline <|> many1 idChar <|> fmap return (noneOf "`") 41 | 42 | htmlEscaped :: CharParser String 43 | htmlEscaped = esc '&' "&" <|> esc '<' "<" <|> esc '>' ">" 44 | where esc c s = char c >> return s 45 | 46 | htmlNewline :: CharParser String 47 | htmlNewline = do 48 | void $ char '\n' 49 | indent <- many (char ' ') 50 | return $ "
" ++ concat (replicate (length indent) " ") 51 | 52 | makeNote :: String -> String 53 | makeNote cont = makeSpanTag "note" ("(" ++ cont ++ ")") 54 | 55 | bqSpecial :: CharParser String 56 | bqSpecial = try $ char '`' >> 57 | ((char '`' >> return "`") 58 | <|> (char '[' >> return "[") 59 | <|> (char ']' >> return "]") 60 | <|> (char '*' >> fmap (makeSpanTag "key") bqGroup) 61 | <|> (char '+' >> fmap (makeSpanTag "op") bqGroup) 62 | <|> (char '$' >> fmap (makeSpanTag "cli") bqGroup) 63 | <|> (char '.' >> fmap (makeSpanTag "builtin") bqGroup) 64 | <|> (char '=' >> fmap (makeSpanTag "val") bqGroup) 65 | <|> (char '%' >> fmap (makeSpanTag "sval") bqGroup) 66 | <|> (char '!' >> fmap (makeSpanTag "error") bqGroup) 67 | <|> (char '#' >> fmap (makeSpanTag "preproc") bqGroup) 68 | <|> (char 'c' >> fmap makeNote bqGroup) 69 | ) 70 | 71 | bqMatching :: Char -> Char -> CharParser String 72 | bqMatching lc rc = do 73 | void $ char lc 74 | ss <- manyTill (((\x -> [lc] ++ x ++ [rc]) <$> bqMatching lc rc) <|> bqAtom) (char rc) 75 | return $ concat ss 76 | 77 | bqGroup :: CharParser String 78 | bqGroup = bqMatching '[' ']' <|> bqAtom 79 | 80 | bqEntry :: CharParser (String, String) 81 | bqEntry = do 82 | void $ string "`e" 83 | void . many1 $ oneOf " \t" 84 | name <- many1 keyChar 85 | void $ many1 space 86 | contAtoms <- manyTill bqAtom (eof <|> void (try $ lookAhead (spaces >> string "`e"))) 87 | spaces 88 | return (name, concat contAtoms) 89 | 90 | type EntryMap = M.Map String String 91 | 92 | bqEntryMap :: CharParser EntryMap 93 | bqEntryMap = do 94 | entries <- many bqEntry 95 | return . M.fromList $ filter (not . all isSpace . snd) entries 96 | 97 | -- parse the entry associations used to create final output 98 | 99 | bqEntryAssoc :: CharParser (String, String) 100 | bqEntryAssoc = do 101 | key <- many1 keyChar 102 | void $ char ':' 103 | void . many1 $ oneOf " \t" 104 | desc <- many1 $ noneOf "\n" 105 | void newline 106 | return (key, desc) 107 | 108 | bqEntryHeading :: CharParser String 109 | bqEntryHeading = do 110 | void $ char '#' 111 | void spaces 112 | heading <- many1 $ noneOf "\n" 113 | void newline 114 | return heading 115 | 116 | type Section = (String, [(String, String)]) 117 | 118 | bqEntrySection :: CharParser Section 119 | bqEntrySection = do 120 | heading <- bqEntryHeading 121 | assocs <- many bqEntryAssoc 122 | return (heading, assocs) 123 | 124 | listSectionKeys :: Section -> [String] 125 | listSectionKeys = map fst . snd 126 | 127 | bqSectionList :: CharParser [Section] 128 | bqSectionList = many bqEntrySection 129 | 130 | type NamedEntryMap = (String, EntryMap) 131 | 132 | -- make everything together! 133 | 134 | buildTd :: String -> NamedEntryMap -> String 135 | buildTd key (name,emap) = case M.lookup key emap of 136 | Nothing -> "" 137 | Just s -> "" ++ s ++ "" 138 | 139 | buildRow :: (String, String) -> [NamedEntryMap] -> String 140 | buildRow (key, desc) emaps = 141 | "
" ++ desc ++ "" ++ concatMap (buildTd key) emaps ++ "" 142 | 143 | makeThRow :: Int -> String -> String -> String 144 | makeThRow colspan key cont = 145 | "" ++ cont ++ "" 146 | 147 | buildColumnHeads :: [NamedEntryMap] -> String 148 | buildColumnHeads emaps = 149 | "" ++ concat ["" ++ name ++ "" | (name,_) <- emaps] ++ "" 150 | 151 | buildSection :: Section -> [NamedEntryMap] -> String 152 | buildSection (heading, assocs) emaps = unlines ( 153 | makeThRow (length emaps) (toKey heading) heading : 154 | buildColumnHeads emaps : [ 155 | buildRow assoc emaps | assoc <- assocs 156 | ]) 157 | 158 | buildTable :: [Section] -> [NamedEntryMap] -> String 159 | buildTable secs emaps = unlines $ [""] 160 | ++ [buildSection sec emaps | sec <- secs] 161 | ++ ["
"] 162 | 163 | buildToC :: [Section] -> String 164 | buildToC secs = "
" ++ intercalate " | " [ 165 | "" ++ heading ++ "" 166 | | (heading, _) <- secs] ++ "
" 167 | 168 | startHTML :: String 169 | startHTML = unlines [ 170 | "", 171 | "", 172 | "Hyperpolymorph", 173 | "", 174 | "", 175 | "", 176 | "", 177 | "
", 178 | "

Hyperpolymorph

", 179 | "

Based on / inspired by Hyperpolyglot.org; released under CC BY-SA 3.0. Work in progress!

", 180 | "Fork me on GitHub", 181 | "
" 182 | ] 183 | footHTML :: String 184 | footHTML = "
" 185 | endHTML :: String 186 | endHTML = unlines ["", ""] 187 | 188 | jsList :: [String] -> String 189 | jsList xs = "[" ++ intercalate "," ["\"" ++ x ++ "\"" | x <- xs] ++ "]" 190 | 191 | buildJsCall :: [String] -> [String] -> [String] -> String 192 | buildJsCall names showNames skeys = unlines [ 193 | "", 194 | "" 198 | ] 199 | 200 | parseIO :: CharParser a -> SourceName -> String -> IO a 201 | parseIO parser msg txt = either (ioError . userError . show) return $ parse parser msg txt 202 | 203 | readEntryMap :: String -> IO EntryMap 204 | readEntryMap name = readFile (name ++ ".txt") >>= parseIO bqEntryMap name 205 | readNamedEntryMap :: String -> IO (String, EntryMap) 206 | readNamedEntryMap name = (,) name <$> readEntryMap name 207 | 208 | unusedEntries :: EntryMap -> [Section] -> [String] 209 | unusedEntries m ss = S.toList $ M.keysSet m S.\\ S.fromList (concatMap listSectionKeys ss) 210 | 211 | -- langNames = ["perl","php","python","ruby","tcl","lua","javascript","groovy","cpp","objective-c","java","c-sharp","c","go","pascal","ada","plpgsql","common-lisp","racket","clojure","c-sharp","ocaml","f-sharp","scala","haskell","prolog","erlang","forth","postscript","factor","posix-shell","applescript","powershell","sql","awk","pig","matlab","r","numpy","fortran","mathematica","sympy","maxima","pari-gp"] 212 | 213 | categorizeLangNames :: [String] -> ([String], [String]) 214 | categorizeLangNames = mconcat . map (\x -> case x of 215 | ('+' : s) -> ([s], [s]) 216 | s -> ([s], [])) 217 | 218 | main :: IO () 219 | main = do 220 | (entryName : langNames0) <- getArgs 221 | let (langNames, showLangNames) = categorizeLangNames langNames0 222 | let entryFile = entryName ++ ".txt" 223 | cont <- readFile entryFile 224 | secs <- parseIO bqSectionList entryFile cont 225 | langs <- mapM readNamedEntryMap langNames 226 | putStrLn startHTML 227 | putStrLn $ buildTable secs langs 228 | putStrLn footHTML 229 | forM_ langs $ \(langName, langMap) -> 230 | case unusedEntries langMap secs of 231 | [] -> return () 232 | xs -> do 233 | hPutStrLn stderr $ "Warning: " ++ langName ++ " has " ++ show (length xs) ++ " unused entries:" 234 | forM_ xs $ hPutStrLn stderr . (" > " ++) 235 | putStrLn $ buildToC secs 236 | putStrLn . buildJsCall langNames showLangNames $ map (toKey . fst) secs 237 | putStrLn endHTML 238 | -------------------------------------------------------------------------------- /morph.js: -------------------------------------------------------------------------------- 1 | 2 | function setDisplay(className, val) { 3 | var elts = document.getElementsByClassName(className); 4 | for (var j = 0; j < elts.length; j++) { 5 | elts[j].style.display = val; 6 | } 7 | } 8 | 9 | function checker(ch, lang) { // force closure capture 10 | return function () { 11 | setDisplay(lang, (ch.checked) ? "table-cell" : "none"); 12 | } 13 | } 14 | 15 | function makeMorpher(langs, showLangs) { 16 | var morpher = document.getElementById("morpher"); 17 | 18 | for (var i = 0; i < langs.length; i++) { 19 | var lang = langs[i]; 20 | 21 | var label = document.createElement("label"); 22 | var ch = document.createElement("input"); 23 | ch.type = "checkbox"; 24 | ch.onclick = checker(ch, lang); 25 | if (showLangs.indexOf(lang) > -1) { 26 | ch.checked = true; 27 | } else { 28 | setDisplay(lang, "none"); 29 | } 30 | 31 | label.appendChild(ch); 32 | label.appendChild(document.createTextNode(lang)); 33 | 34 | morpher.appendChild(label); 35 | } 36 | } 37 | 38 | var scrollsel = -1; 39 | function makeToCScroller(ids) { 40 | var tocLinks = document.getElementById("toc").getElementsByTagName("a"); 41 | window.onscroll = function () { 42 | var i; 43 | for (i = 0; i < ids.length; i++) { 44 | if (document.getElementById(ids[i]).getBoundingClientRect().top > 10) 45 | break; 46 | } 47 | i--; 48 | if (i != scrollsel) { 49 | if (i != -1) tocLinks[i].className = "ts"; 50 | if (scrollsel != -1) tocLinks[scrollsel].className = ""; 51 | scrollsel = i; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /objective-c.txt: -------------------------------------------------------------------------------- 1 | `e version-used 2 | gcc 4.2 3 | `e show-version 4 | $ gcc --version 5 | `e implicit-prologue 6 | 7 | `e hello-world 8 | $ cat hello.m 9 | 10 | #include 11 | 12 | 13 | int main(int argc, char **argv) { 14 | printf("Hello, World!\n"); 15 | 16 | } 17 | 18 | 19 | $ gcc hello.m 20 | 21 | 22 | $ ./a.out 23 | `e file-suffixes 24 | Foo.m 25 | 26 | Foo.h 27 | 28 | Foo.o 29 | `e block-delimiters 30 | { } 31 | `e statement-terminator 32 | ; 33 | `e top-level-statements 34 | 35 | `e end-of-line-comment 36 | // comment 37 | `e multiple-line-comment 38 | /* comment 39 | 40 | another comment */ 41 | `e local-variable 42 | int i; 43 | 44 | int j = 3; 45 | `e uninitialized-local-variable 46 | behavior is undefined. 47 | 48 | 49 | Most implementations do not zero-initialize stack variables, so the value will be whatever happened to be in memory. 50 | `e global-variable 51 | in foo.cpp outside of any function or class definition: 52 | 53 | int foo = 7; 54 | 55 | in bar.cpp outside of any function or class definition: 56 | 57 | extern int foo; 58 | `e uninitialized-global-variable 59 | 60 | `e constant 61 | const int i = 7; 62 | `e assignment 63 | 64 | `e compound-assignment-arithmetic-string-logical-bit 65 | 66 | `e increment-and-decrement 67 | 68 | `e address 69 | 70 | `e dereference 71 | 72 | `e type-size 73 | 74 | `e address-arithmetic 75 | 76 | `e unique-pointer 77 | 78 | `e reference-count-pointer 79 | 80 | `e weak-pointer 81 | 82 | `e allocate-heap 83 | #include 84 | 85 | 86 | int *ip = malloc(sizeof(int)); 87 | `e uninitialized-heap 88 | 89 | `e free-heap 90 | #include 91 | 92 | 93 | free(ip); 94 | `e null 95 | NULL 96 | `e coalesce 97 | NSString *s1 = s2 || @"was null"; 98 | `e boolean-type 99 | BOOL 100 | `e true-and-false 101 | YES NO 102 | `e falsehoods 103 | 0 0.0 NULL 104 | `e logical-operators 105 | && || ! 106 | `e relational-operators 107 | == != < > <= >= 108 | `e integer-type 109 | signed char 1+ byte 110 | 111 | short int 2+ bytes 112 | 113 | int 2+ bytes 114 | 115 | long int 4+ bytes 116 | 117 | long long int 4+ bytes 118 | `e unsigned-type 119 | unsigned char: 8+ 120 | 121 | unsigned short int 2 bytes+ 122 | 123 | unsigned int 2 bytes+ 124 | 125 | unsigned long int 4+ bytes 126 | 127 | unsigned long long int 4+ bytes 128 | `e float-type 129 | float 130 | 131 | double 132 | 133 | long double 134 | `e fixed-type 135 | none 136 | `e arithmetic-operators 137 | + - * / % 138 | `e integer-division 139 | // evaluates to 2: 140 | 141 | 7 / 3 142 | `e integer-division-by-zero 143 | process sent a SIGFPE signal 144 | `e float-division 145 | 7 / (float)3 146 | `e float-division-by-zero-dividend-is-positive-zero-negative 147 | inf 148 | 149 | nan 150 | 151 | -inf 152 | 153 | there are no portably defined literals or constants for the above values. 154 | `e power 155 | #include 156 | 157 | 158 | pow(2.0, 32.0); 159 | `e sqrt 160 | #include 161 | 162 | 163 | sqrt(2) 164 | `e sqrt-1 165 | nan 166 | `e transcendental-functions 167 | #include 168 | 169 | 170 | exp log log2 log10 171 | 172 | sin cos tan 173 | 174 | asin acos atan 175 | 176 | atan2 177 | `e transcendental-constants 178 | #include 179 | 180 | 181 | M_E 182 | 183 | M_PI 184 | `e float-truncation 185 | #include 186 | 187 | 188 | double d = 3.77; 189 | 190 | 191 | long trnc = (long)d; 192 | 193 | long rnd = round(d); 194 | 195 | long flr = floorl(d); 196 | 197 | long cl = ceill(d); 198 | `e absolute-value-and-signum 199 | #include // abs() 200 | 201 | #include // fabs() 202 | 203 | 204 | int i = -7; 205 | 206 | int ai = abs(i); 207 | 208 | 209 | float x = -7.77; 210 | 211 | float ax = fabs(x); 212 | `e integer-overflow 213 | modular arithmetic 214 | 215 | 216 | The C standard does not define behavior for signed integers, however. 217 | `e float-overflow 218 | no behavior defined by standard; many implementations return inf 219 | `e float-limits-largest-finite-float-smallest-positive-float 220 | 221 | `e complex-construction 222 | 223 | `e complex-decomposition-real-and-imaginary-component-argument-absolute-value-conjugate 224 | 225 | `e random-number-uniform-integer-uniform-float-normal-float 226 | #include 227 | 228 | // assuming 100 much smaller than RAND_MAX: 229 | 230 | int i = rand() % 100; 231 | 232 | double x = drand48(); 233 | none 234 | `e random-seed 235 | 236 | `e bit-operators 237 | << >> & | ^ ~ 238 | `e binary-octal-and-hex-literals 239 | 240 | `e radix-convert-integer-to-and-from-string-with-radix 241 | 242 | `e string-type 243 | NSString* s = @"lorem ipsum"; 244 | 245 | // convert to C string: 246 | 247 | const char* s2 = [s UTF8String]; 248 | `e string-literal 249 | @"don't say \"no"" 250 | `e newline-in-literal 251 | string literals can extend over multiple lines, but the newlines do not appear in the resulting string 252 | `e literal-escapes 253 | \a \b \f \n \r \t \v 254 | 255 | \\ \" \' 256 | 257 | \xhh \o \oo \ooo 258 | `e allocate-string 259 | NSString *s = @"hello"; 260 | `e are-strings-mutable 261 | 262 | `e copy-string 263 | 264 | `e format 265 | [NSString stringWithFormat:@"%@: %d", @"Spain", 7] 266 | `e compare-strings 267 | [@"hello" compare:@"hello"] 268 | `e concatenate 269 | NSString *s1 = @"hello"; 270 | 271 | NSString *s2 = @" world"; 272 | 273 | NSString *s3 = [s1 stringByAppendingString:s2]; 274 | `e replicate 275 | 276 | `e translate-case 277 | [@"HELLO" lowercaseString] 278 | `e trim 279 | [@" hello " stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] 280 | `e pad 281 | [@"hello" stringByPaddingToLength:10 withString:@" " startingAtIndex:0] 282 | `e number-to-string 283 | 284 | `e string-to-number 285 | [@"14" integerValue] 286 | 287 | [@"14" longLongvalue] 288 | 289 | [@"14.7" floatValue] 290 | 291 | [@"14.7" doubleValue] 292 | `e join 293 | 294 | `e split 295 | [@"Bob Ned Amy" componentsSeparatedByString:@" "] 296 | `e serialize 297 | 298 | `e string-length 299 | [s length] 300 | `e index-of-substring 301 | [@"hello" rangeOfString:@"ll"].location 302 | `e extract-substring 303 | [@"hello" substringWithRange:NSMakeRange(2, 2)] 304 | `e character-type 305 | 306 | `e character-literal 307 | 308 | `e test-character 309 | 310 | `e regex-type 311 | 312 | `e character-class-abbreviations 313 | 314 | `e anchors 315 | 316 | `e lookahead-positive-negative 317 | 318 | `e match-test 319 | NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @".*ll.*"]; 320 | 321 | BOOL is_match = [pred evaluateWithObject:@"hello"]; 322 | `e case-insensitive-match-test 323 | 324 | `e modifiers 325 | 326 | `e substitution 327 | 328 | `e match-prematch-postmatch 329 | 330 | `e group-capture 331 | 332 | `e date-time-type 333 | 334 | `e current-date-time 335 | 336 | `e to-unix-epoch-from-unix-epoch 337 | 338 | `e date-and-time-to-string 339 | 340 | `e format-date 341 | 342 | `e parse-date 343 | 344 | `e date-subtraction 345 | 346 | `e add-duration 347 | 348 | `e date-parts 349 | 350 | `e time-parts 351 | 352 | `e declare-on-stack 353 | int a[10]; 354 | `e declare-on-heap 355 | #include 356 | 357 | int *a = calloc(10, sizeof(int)); 358 | `e free-heap 359 | #include 360 | 361 | free(a); 362 | `e list-literal 363 | NSArray *a = [NSArray arrayWithObjects:@"hello", @"goodbye", nil]; 364 | `e list-size 365 | [a count] 366 | `e list-lookup 367 | [a objectAtIndex:0] 368 | `e list-update 369 | 370 | `e list-out-of-bounds 371 | raises NSRangeException exception 372 | `e copy 373 | 374 | `e as-function-argument 375 | 376 | `e iterate-over-elements 377 | NSEnumerator *i = [a objectEnumerator]; 378 | 379 | id o; 380 | 381 | while (o = [i nextObject]) { 382 | do something with o 383 | 384 | } 385 | `e sort 386 | 387 | `e list-name 388 | NSMutableArray (?) 389 | `e list-declare 390 | NSMutableArray *a = [NSMutableArray arrayWithCapacity:10]; 391 | `e list-size 392 | [a count] 393 | `e capacity-get-increase 394 | 395 | `e empty-test-and-clear 396 | 397 | `e lookup 398 | [a objectAtIndex:0] 399 | `e update 400 | 401 | `e out-of-bounds 402 | raises NSRangeException 403 | `e index-of-element 404 | 405 | `e slice 406 | 407 | `e drop 408 | 409 | `e manipulate-back 410 | [a addObject:@"hello"]; 411 | 412 | [a removeLastObject]; 413 | `e manipulate-front 414 | 415 | `e concatenate 416 | 417 | `e list-replicate 418 | 419 | `e copy 420 | 421 | `e array-as-function-argument 422 | 423 | `e iterate-over-elements 424 | NSEnumerator *i = [a objectEnumerator]; 425 | 426 | id o; 427 | 428 | while (o = [i nextObject]) { 429 | do something with o 430 | 431 | } 432 | `e iterate-over-indices-and-elements 433 | 434 | `e reverse 435 | 436 | `e sort 437 | 438 | `e dedupe 439 | 440 | `e membership 441 | 442 | `e intersection 443 | 444 | `e union 445 | 446 | `e relative-complement-symmetric-difference 447 | 448 | `e map 449 | 450 | `e filter 451 | 452 | `e fold-from-left 453 | 454 | `e min-and-max-element 455 | 456 | `e shuffle-and-sample 457 | 458 | `e zip 459 | 460 | `e declare-pair 461 | 462 | `e lookup-pair-elements 463 | 464 | `e update-pair-elements 465 | 466 | `e declare-tuple 467 | 468 | `e lookup-tuple-elements 469 | 470 | `e update-tuple-elements 471 | 472 | `e tuple-size 473 | 474 | `e create-references-for-tuple-elements 475 | 476 | `e map-declaration 477 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:10]; 478 | `e map-access 479 | [dict setObject:@"5" forKey:@"hello"]; 480 | 481 | [dict objectForKey:@"hello"] 482 | `e map-size 483 | [dict count] 484 | `e map-remove-element 485 | [dict removeObjectForKey:@"hello"]; 486 | `e map-element-not-found-result 487 | NULL 488 | `e map-iterate 489 | NSEnumerator *i = [dict keyEnumerator]; 490 | 491 | id key; 492 | 493 | while ((key = [i nextObject])) { 494 | do something with key 495 | 496 | } 497 | `e declare-function 498 | 499 | `e define-function 500 | 501 | `e invoke-function 502 | 503 | `e define-static-class-method 504 | 505 | `e invoke-static-class-method 506 | 507 | `e overload-function 508 | method overloading only 509 | `e default-argument 510 | none 511 | `e variable-number-of-arguments 512 | use C; use method overloading for finite arities 513 | `e named-parameters 514 | +(float)weight: (float) w height: (float) h { 515 | return (w * 703) / (h * h); 516 | 517 | } 518 | 519 | +(float)height: (float) h weight: (float) w { 520 | return [BMI weight: w height: h]; 521 | 522 | } 523 | 524 | [BMI weight:155 height:70]; 525 | 526 | [BMI height:70 weight:155]; 527 | `e pass-by-value 528 | void use_integer(int i) { 529 | function body 530 | 531 | } 532 | 533 | int i = 7; 534 | 535 | use_integer(i); 536 | `e pass-by-reference 537 | none 538 | `e pass-by-address 539 | void use_iptr(int *i) { 540 | function body 541 | 542 | } 543 | 544 | int i = 7; 545 | 546 | use_iptr(&i); 547 | `e return-value 548 | 549 | `e no-return-value 550 | 551 | `e recursive-function 552 | 553 | `e lambda 554 | 555 | `e invoke-lambda 556 | 557 | `e closure 558 | 559 | `e function-with-private-state 560 | 561 | `e function-as-value 562 | 563 | `e overload-operator 564 | none 565 | `e if 566 | if (i>0) { 567 | signum = 1; 568 | 569 | } else if (i==0) { 570 | signum = 0; 571 | 572 | } else { 573 | signum = -1; 574 | 575 | } 576 | `e dangling-else 577 | 578 | `e switch 579 | switch(i) { 580 | 581 | case 0: 582 | 0; 583 | break; 584 | 585 | case 1: 586 | 1; 587 | break; 588 | 589 | default: 590 | -1; 591 | break; 592 | 593 | } 594 | `e while 595 | int i = 0; 596 | 597 | while (i<10) { 598 | … 599 | i++; 600 | 601 | } 602 | `e for 603 | int i, n; 604 | 605 | for (i=1,n=1; i<=10; i++) { 606 | n *= i; 607 | 608 | } 609 | `e break 610 | 611 | `e break-out-of-nested-loops 612 | 613 | `e continue 614 | 615 | `e goto 616 | 617 | `e base-exception 618 | 619 | `e predefined-exceptions 620 | 621 | `e raise-exception 622 | NSException *exc = [NSException exceptionWithName:@"error" reason:@"failed" userInfo:nil]; 623 | 624 | @throw exc; 625 | `e handle-exception 626 | @try { 627 | [NSException raise:@"error" format:@"failed"]; 628 | 629 | } @catch (NSException *e) { 630 | printf([[e reason] UTF8String]); 631 | 632 | } 633 | `e define-exception 634 | 635 | `e re-raise-exception 636 | 637 | `e catch-all-handler 638 | 639 | `e multiple-handlers 640 | 641 | `e uncaught-exception-behavior 642 | 643 | `e error-message 644 | 645 | `e system-call-errno 646 | 647 | `e finally 648 | @try { 649 | risky code 650 | 651 | } @finally { 652 | perform cleanup 653 | 654 | } 655 | `e exception-specification 656 | no 657 | `e start-thread 658 | 659 | `e terminate-current-thread 660 | 661 | `e terminate-other-thread 662 | 663 | `e list-threads 664 | 665 | `e wait-on-thread 666 | 667 | `e lock 668 | 669 | `e create-message-queue 670 | 671 | `e send-message 672 | 673 | `e receive-message 674 | 675 | `e standard-file-handles 676 | 677 | `e printf 678 | printf("count: %d\n", 7); 679 | `e read-from-file 680 | NSError *error = nil; 681 | 682 | NSString *s = [NSString stringWithContentsOfFile: @"/etc/passwd" encoding:NSUTF8StringEncoding error:&error]; 683 | 684 | if ( error != nil ) { 685 | handle error 686 | 687 | } 688 | 689 | NSArray *a = [s componentsSeparatedByString:@"\n"]; 690 | 691 | id line; 692 | 693 | while (line = [i nextObject]) { 694 | process line 695 | 696 | } 697 | `e write-to-file 698 | 699 | `e file-exists-test-regular-test 700 | 701 | `e file-size 702 | 703 | `e is-file-readable-writable-executable 704 | 705 | `e set-file-permissions 706 | 707 | `e copy-file-remove-file-rename-file 708 | 709 | `e csv 710 | 711 | `e json 712 | 713 | `e build-xml 714 | 715 | `e parse-xml 716 | 717 | `e parse-html 718 | 719 | `e build-pathname 720 | 721 | `e dirname-and-basename 722 | 723 | `e absolute-pathname 724 | 725 | `e iterate-over-directory-by-file 726 | 727 | `e glob-paths 728 | 729 | `e make-directory 730 | 731 | `e recursive-copy 732 | 733 | `e remove-empty-directory 734 | 735 | `e remove-directory-and-contents 736 | 737 | `e directory-test 738 | 739 | `e generate-unused-directory-name 740 | 741 | `e system-temporary-file-directory 742 | 743 | `e signature-of-main 744 | int main(int argc, char **argv) { 745 | `e first-argument 746 | pathname of executable 747 | `e environment-variable 748 | NSString *home = [[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]; 749 | `e iterate-through-environment-variables 750 | NSEnumerator *i = [[[NSProcessInfo processInfo] environment] keyEnumerator]; 751 | 752 | id key; 753 | 754 | while ((key = [i nextObject])) { 755 | use NSString key 756 | 757 | } 758 | `e standard-library-name 759 | Foundation Framework 760 | `e declare-namespace 761 | 762 | `e multiple-namespaces-per-file 763 | 764 | `e namespaces-map-to-directories 765 | 766 | `e import-namespace 767 | 768 | `e import-part-of-namespace 769 | 770 | `e import-symbol 771 | 772 | `e import-static-symbol 773 | 774 | `e import-position 775 | 776 | `e using-a-symbol-that-hasn-t-been-imported 777 | 778 | `e application-environment 779 | 780 | `e multiple-installations 781 | 782 | `e package-manager 783 | 784 | `e type-synonym 785 | typedef int customer_id; 786 | 787 | customer_id cid = 3; 788 | `e enum 789 | enum day_of_week { mon, tue, wed, thu, fri, sat, sun }; 790 | 791 | enum day_of_week d = tue; 792 | `e struct-definition 793 | struct medal_count { 794 | const char* country; 795 | int gold; 796 | int silver; 797 | int bronze; 798 | 799 | }; 800 | `e struct-declaration 801 | struct medal_count spain; 802 | `e struct-initialization 803 | struct medal_count spain = { "Spain", 3, 7, 4}; 804 | 805 | struct medal_count france = { .gold = 8, .silver = 7, .bronze = 9, .country = "France" }; 806 | `e struct-member-assignment 807 | spain.country = "Spain"; 808 | 809 | spain.gold = 3; 810 | 811 | spain.silver = 7; 812 | 813 | spain.bronze = 4; 814 | `e struct-member-access 815 | int spain_total = spain.gold + spain.silver + spain.bronze; 816 | `e define-generic-type 817 | 818 | `e instantiate-generic-type 819 | 820 | `e generic-function 821 | 822 | `e generic-array 823 | 824 | `e value-parameter 825 | 826 | `e template-parameter 827 | 828 | `e template-specialization 829 | 830 | `e multiple-type-parameters 831 | 832 | `e generic-type-parameters 833 | 834 | `e template-parameters 835 | 836 | `e variadic-template 837 | 838 | `e semantics-of 839 | object identity comparison 840 | `e define-class 841 | Rational.h: 842 | 843 | #import 844 | 845 | @interface Rational : NSObject { 846 | int num; 847 | int denom; 848 | 849 | } 850 | 851 | @property int num, denom; 852 | 853 | -(Rational*) initWith: (int) n: (int) d; 854 | 855 | -(Rational*) add: (Rational *) o; 856 | 857 | @end 858 | Rational.m: 859 | 860 | #include "Rational.h" 861 | 862 | @implementation Rational 863 | 864 | @synthesize num, denom; 865 | 866 | -(Rational*) add: (Rational*) o { 867 | int sum_n = self.num * o.denom + o.num * self.denom; 868 | int sum_d = self.denom * o.denom; 869 | Rational* sum = [[Rational alloc] initWith: sum_n: sum_d]; 870 | return sum; 871 | 872 | } 873 | 874 | @end 875 | `e class-definition-location 876 | top level 877 | `e constructor 878 | -(Rational*) initWith: (int) n: (int) d { 879 | self = [super init]; 880 | if (self) { 881 | self.num = n; 882 | self.denom = d; 883 | } 884 | return self; 885 | 886 | } 887 | `e create-object 888 | Rational *r = [[Rational alloc] initWith: 7: 3]; 889 | `e destructor 890 | -(void) dealloc { 891 | [super dealloc]; 892 | printf("deallocated…"); 893 | 894 | } 895 | `e destroy-object 896 | [r release]; 897 | `e define-method 898 | -(int) height { 899 | if ( abs(self.num) > abs(self.denom) ) { 900 | return abs(self.num); 901 | } 902 | return abs(self.denom); 903 | 904 | } 905 | `e invoke-method 906 | [r1 height]; 907 | `e define-class-method 908 | precede definition with +: 909 | 910 | +(Rational*) max: (Rational*) a: (Rational*) b { 911 | if ( a.num * b.denom > b.num * a.denom ) { 912 | return a; 913 | } 914 | return b; 915 | 916 | } 917 | `e invoke-class-method 918 | 919 | `e name-of-receiver 920 | self 921 | `e access-control 922 | access keywords define regions: 923 | 924 | @interface Foo : NSObject { 925 | int protectedInt1; 926 | int protectedInt2; 927 | 928 | @public 929 | int publicInt1; 930 | int publicInt2; 931 | 932 | @protected 933 | int protectedInt3; 934 | int protectedInt4; 935 | 936 | @private 937 | int privateInt1; 938 | int privateInt2; 939 | 940 | } 941 | 942 | @end 943 | `e anonymous-class 944 | none 945 | `e dynamic-dispatch 946 | dispatch always dynamic 947 | `e static-dispatch 948 | dispatch always dynamic 949 | `e subclass 950 | 951 | `e invoking-superclass-constructor 952 | 953 | `e mark-class-underivable-or-method-unoverrideable 954 | none 955 | `e root-class 956 | NSObject 957 | `e root-class-methods 958 | autorelease 959 | 960 | class 961 | 962 | conformsToProtocol: 963 | 964 | hash 965 | 966 | isEqual: 967 | 968 | isKindOfClass: 969 | 970 | isProxy 971 | 972 | performSelector: 973 | 974 | performSelector:withObject: 975 | 976 | performSelector:withObject:withObject: 977 | 978 | release 979 | 980 | respondsToSelector: 981 | 982 | retain 983 | 984 | retainCount 985 | 986 | self 987 | 988 | superclass 989 | `e get-type-class-of-object 990 | 991 | `e get-type-class-from-string 992 | 993 | `e get-type-class-from-type-identifier 994 | 995 | `e class-name 996 | 997 | `e get-methods 998 | 999 | `e has-method 1000 | 1001 | `e invoke-method-object 1002 | 1003 | `e get-local-hostname-dns-lookup-reverse-dns-lookup 1004 | 1005 | `e http-get 1006 | 1007 | `e http-post 1008 | 1009 | `e absolute-url 1010 | 1011 | `e parse-url 1012 | 1013 | `e url-encode-decode 1014 | 1015 | `e base64-encode-decode 1016 | 1017 | `e test-class 1018 | 1019 | `e run-all-tests 1020 | 1021 | `e equality-assertion 1022 | 1023 | `e approximate-assertion 1024 | 1025 | `e exception-assertion 1026 | 1027 | `e setup 1028 | 1029 | `e teardown 1030 | 1031 | `e stronger-warnings 1032 | 1033 | `e suppress-warnings 1034 | 1035 | `e treat-warnings-as-errors 1036 | 1037 | `e run-debugger 1038 | 1039 | `e debugger-commands-help-list-source-re-load-executable-next-step-set-breakpoint-show-breakpoints-delete-breakpoint-continue-backtrace-up-stack-down-stack-print-run-quit 1040 | 1041 | `e benchmark-code 1042 | 1043 | `e profile-code 1044 | 1045 | `e memory-tool 1046 | 1047 | -------------------------------------------------------------------------------- /ocaml.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | 4.0 3 | `e show-version 4 | `$[ocaml -version] 5 | `e interpreter 6 | `$[echo 'print_endline "hello"' > hello.ml] 7 | `$[ocaml hello.ml] 8 | `e shebang 9 | `$[cat < hello.ml] 10 | #!/usr/bin/env ocaml 11 | print_endline "hello";; 12 | EOF 13 | 14 | `$[chmod +x hello.ml] 15 | `$[./hello.ml] 16 | `e bytecode-compiler-and-interpreter 17 | `$[echo 'print_endline "hello";;' > hello.ml] 18 | `$[ocamlc -o hello hello.ml] 19 | `$[ocamlrun hello] 20 | `e native-compiler 21 | `$[echo 'print_endline "hello";;' > hello.ml] 22 | `$[ocamlopt hello.ml -o hello] 23 | `$[./hello] 24 | `e library-which-is-always-imported 25 | Pervasives 26 | `e statement-terminator 27 | ;; 28 | `e block-delimiters 29 | ( expr ; … ) 30 | 31 | begin expr ; … end 32 | `e end-of-line-comment 33 | `e multiple-line-comment 34 | (* comment 35 | another comment *) 36 | `e constant 37 | `*let n = 1 + 2;; 38 | `e local-variable 39 | `*let n = `*ref 3;; 40 | n := 4;; 41 | !n + 7;; 42 | `e unit-type-and-value 43 | unit 44 | () 45 | `e conditional-expression 46 | `*let n = -3;; 47 | `*let absn = `*if n < 0 `*then -n `*else n;; 48 | `e branch-type-mismatch 49 | `![compilation error:] 50 | 51 | `*if `=true `*then "hello" `*else 3;; 52 | `e null 53 | `.None `c[type 'a option] 54 | `e nullable-type 55 | `*type list_option_int = `.int option list;; 56 | 57 | 58 | `*let list = [`.Some 3; `.None; `.Some (-4)];; 59 | `e null-test 60 | `*match foo `*with 61 | | `.None -> `=true 62 | | _ -> `=false;; 63 | `e coalesce 64 | `*match foo `*with 65 | | `.None -> 0 66 | | `.Some n -> n;; 67 | `e nullif 68 | `*match foo `*with 69 | | -999 -> `.None 70 | | n -> `.Some n;; 71 | `e expression-type-declaration 72 | `.float 1 73 | `e let-in 74 | `*let z = 75 | `*let x = 3.0 in 76 | `*let y = 2.0 *. x in 77 | x *. y;; 78 | `e where 79 | none 80 | `e boolean-type 81 | bool 82 | `e true-and-false 83 | `=true `=false 84 | `e logical-operators 85 | && || not 86 | `e relational-operators 87 | `+[= <> < > <= >=] 88 | `[== !=] `c[warning: == and != test for "physical equality"] 89 | `e min-and-max 90 | min 1 2 91 | max 1 2 92 | `e integer-type 93 | `.int 94 | `c[other integer types:] 95 | int32 int64 nativeint 96 | `e integer-literal 97 | `.int, int64, and nativeint literals: 98 | 12 12L 12n 99 | `c[literals can contain underscores:] 100 | 1_000_000 101 | `c[this parses as an expression:] 102 | -4 103 | `e float-type 104 | `.float 105 | `e integer-operators 106 | `+[+ - * /] `*mod 107 | `c[mod is an infix operator, and is signed like % or rem in other languages] 108 | `e float-operators 109 | `+[+. -. *. /.] 110 | `e add-integer-and-float 111 | `.float 3 `+[+.] 7.0 112 | `e divmod 113 | 7 `+/ 3 114 | 7 `*mod 3 115 | `e integer-division-by-zero 116 | raises Division_by_zero 117 | `e float-division 118 | `.float 7 /. `.float 3 119 | `e float-division-by-zero 120 | infinity nan or neg_infinity 121 | `e power 122 | 2.0 ** 32.0 123 | `e sqrt 124 | sqrt 2.0 125 | `e sqrt-1 126 | sqrt (-1.0): 127 | nan 128 | `e transcendental-functions 129 | exp log 130 | sin cos tan 131 | asin acos atan atan2 132 | `e transcendental-constants 133 | 4.0 *. atan 1.0 134 | exp 1.0 135 | `e float-truncation 136 | truncate 3.14 137 | `c[none] 138 | floor 3.14 `c[returns float] 139 | ceil 3.14 `c[returns float] 140 | `e absolute-value-and-signum 141 | abs (-7) 142 | abs_float (-7.0) 143 | no signum 144 | `e integer-overflow 145 | modular arithmetic 146 | `e float-overflow 147 | infinity 148 | `e arbitrary-length-integer 149 | open Big_int;; 150 | 151 | `*let n = big_int_of_int 7;; 152 | `*let m = big_int_of_int 12;; 153 | `e arbitrary-length-integer-operators 154 | add_big_int n m 155 | sub_big_int n m 156 | mult_big_int n m 157 | div_big_int n m (* quotient *) 158 | mod_big_int n m 159 | eq_big_int n m 160 | lt_big_int n m 161 | gt_big_int n m 162 | le_big_int n m 163 | ge_big_int n m 164 | `e rational-type 165 | `e rational-construction 166 | `e rational-decomposition 167 | `e complex-type 168 | Complex.t 169 | `e complex-constants 170 | Complex.zero 171 | Complex.one 172 | Complex.i 173 | `e complex-operators 174 | Complex.add z w;; 175 | Complex.sub z w;; 176 | Complex.mul z w;; 177 | Complex.div z w;; 178 | `e complex-construction 179 | {Complex.re=1.0; Complex.im=2.0} 180 | `e complex-decomposition 181 | `*let z = {Complex.re=1.0; Complex.im=2.0};; 182 | 183 | z.Complex.re;; 184 | z.Complex.im;; 185 | Complex.arg z;; 186 | Complex.norm z;; 187 | Complex.conj z;; 188 | `e random-number-uniform-integer-uniform-float-normal-float 189 | Random.int 100 190 | Random.float 1.0 191 | `c[none] 192 | `e random-seed 193 | Random.init 17;; 194 | `*let seed = Random.get_state();; 195 | Random.set_state seed;; 196 | `e bit-operators 197 | 1 lsl 4 198 | 199 | 1 lsr 4 200 | 201 | 1 land 3 202 | 203 | 1 lor 3 204 | 205 | 1 lxor 3 206 | 207 | lnot 1 208 | `e binary-octal-and-hex-literals 209 | `=0b101010 210 | `=0o52 211 | `=0x2a 212 | `e radix-convert-integer-to-and-from-string-with-radix 213 | 214 | `e string-type 215 | string 216 | `e string-literal 217 | `=["Hello, World!"] 218 | `e newline-in-literal 219 | no 220 | `e literal-escapes 221 | `%[\b \n \r \t \" \' \\] 222 | 223 | `%[\ooo \xhh] 224 | `e format 225 | 226 | `e concatenate-strings 227 | `=["Hello"] `+^ `=[", "] `+^ `=["World!"] 228 | `e replicate-string 229 | String.make 80 '-' 230 | `e translate-case 231 | String.uppercase "hello" 232 | 233 | String.lowercase "HELLO" 234 | `e capitalize 235 | String.capitalize "hello" 236 | `e trim 237 | String.trim " hello " 238 | `e pad 239 | 240 | `e number-to-string 241 | `=["two: "] `+^ string_of_int `=2 242 | 243 | `=["pi: "] `+^ float_of_string `=[3.14] 244 | `e string-to-number 245 | `=[7] `++ int_of_string `=["12"] 246 | 247 | `=[73.9] `+[+.] float_of_string `=[".037"] 248 | `e join 249 | 250 | `e split 251 | 252 | `e character-type 253 | char 254 | `e character-literal 255 | `=['h'] 256 | `e string-length 257 | String.length "hello" 258 | `e index-of-substring 259 | 260 | `e extract-substring 261 | String.sub "hello" 0 4 262 | `e extract-character 263 | `=["hello"].[0] 264 | `e chr-and-ord 265 | Char.code 'a' 266 | 267 | Char.chr 97 268 | `e date-time-type 269 | 270 | `e current-date-time 271 | 272 | `e current-unix-epoch 273 | open Unix;; 274 | 275 | (* float: *) 276 | 277 | time();; 278 | `e size 279 | 280 | `e lookup 281 | 282 | `e update 283 | 284 | `e out-of-bounds 285 | 286 | `e list-literal 287 | [1; 2; 3] 288 | `e empty-list 289 | [] 290 | `e empty-test 291 | `*let list = [1; 2; 3];; 292 | 293 | 294 | list == [] 295 | `e cons 296 | 1 :: [2; 3] 297 | `e head 298 | List.hd [1; 2; 3] 299 | `e tail 300 | List.tl [1; 2; 3] 301 | `e head-and-tail-of-empty-list 302 | exceptions 303 | `e string-length 304 | List.length [1; 2; 3] 305 | `e list-lookup 306 | List.nth [1; 2; 3] 0 307 | `e index-of-element 308 | 309 | `e update 310 | 311 | `e concatenate-two-lists-list-of-lists 312 | [1; 2] @ [3; 4] 313 | 314 | List.append [1; 2] [3; 4] 315 | 316 | 317 | List.concat [[1; 2]; [3; 4]] 318 | `e last-and-butlast 319 | 320 | `e take 321 | 322 | `e drop 323 | 324 | `e iterate-over-elements 325 | `*let f i = 326 | print_endline (string_of_int i);; 327 | 328 | 329 | List.iter f [1; 2; 3];; 330 | `e reverse 331 | List.rev [1; 2; 3] 332 | `e sort 333 | List.sort min [1; 3; 2; 4] 334 | 335 | List.sort max [1; 3; 2; 4] 336 | `e map 337 | List.map (( * ) 2) [1; 2; 3] 338 | `e filter 339 | List.filter ((<) 2) [1; 2; 3] 340 | `e fold-from-left 341 | List.fold_left (+) 0 [1; 2; 3] 342 | `e fold-from-right 343 | List.fold_right (-) [1; 2; 3] 0 344 | `e membership 345 | 346 | `e universal-test 347 | List.for_all (fun x -> x > 2) [1; 2; 3];; 348 | `e existential-test 349 | List.exists (fun x -> x > 2) [1; 2; 3];; 350 | `e zip-lists 351 | 352 | `e tuple 353 | (1, "hello", `=true) 354 | `e tuple-element-access 355 | `*match (1, "hello", `=true) `*with _, x, _ -> x 356 | `e pair-element-access 357 | fst (12, "December") 358 | 359 | snd (12, "December") 360 | `e define-function 361 | `*let average a b = ( a +. b ) /. 2.0;; 362 | `e invoke-function 363 | (* 4.5: *) 364 | 365 | average 1.0 2.0 +. 3.0;; 366 | 367 | (* 3.0: *) 368 | 369 | average 1.0 (2.0 +. 3.0);; 370 | `e define-function-with-block-body 371 | 372 | `e named-parameters 373 | `*let subtract ~m ~s = m - s;; 374 | 375 | 376 | subtract ~s: 3 ~m: 7;; 377 | `e named-parameter-default-value 378 | `*let logarithm ?(base = (exp 1.0)) x = log x /. (log base);; 379 | 380 | 381 | logarithm 2.718;; 382 | 383 | logarithm ~base: 2.0 10.0;; 384 | `e piecewise-defined-function 385 | `*let to_s = function Red -> "red" 386 | | Green -> "green" 387 | | Blue -> "blue";; 388 | `e recursive-function 389 | `*let rec range a b = 390 | 391 | `*if a > b `*then [] 392 | 393 | `*else a :: range (a+1) b;; 394 | `e mutually-recursive-functions 395 | `*let rec even n = `*if n = 0 `*then `=true `*else odd (n-1) 396 | 397 | and odd n = `*if n = 0 `*then `=false `*else even (n-1);; 398 | `e lambda 399 | fun x -> fun y -> (x +. y) /. 2.0 400 | `e infix-operator-in-prefix-position 401 | ( * ) 3 4;; 402 | `e function-in-infix-position 403 | none 404 | `e currying 405 | `*let plus2 = (+) 2;; 406 | `e composition 407 | 408 | `e function-composition-operator 409 | none 410 | `e lazy-evaluation 411 | `*let arg1 x y = x;; 412 | 413 | 414 | arg1 7 (lazy (1/0) );; 415 | `e strict-evaluation 416 | default behavior 417 | `e if 418 | `*if x > 0 `*then 419 | print_endline "pos";; 420 | `e control-structure-keywords 421 | `*if x > 0 `*then 422 | print_endline "pos" 423 | `*else 424 | `*if x < 0 `*then 425 | print_endline "neg" 426 | `*else 427 | print_endline "zero";; 428 | `e sequencing 429 | print_endline "one"; 430 | 431 | print_endline "two"; 432 | 433 | print_endline "three";; 434 | `e while 435 | `*let i = ref 0;; 436 | 437 | 438 | while !i < 10 do 439 | print_endline (string_of_int !i); 440 | i := !i + 1 441 | 442 | done;; 443 | `e for 444 | for i = 1 to 10 do 445 | `*let s = string_of_int i in 446 | print_endline s 447 | 448 | done;; 449 | `e for-in-reverse 450 | for i = 10 downto 1 do 451 | `*let s = string_of_int i in 452 | print_endline s 453 | 454 | done;; 455 | `e list-iteration 456 | none 457 | `e loop 458 | `*let rec loop i = 459 | `*if i <= 10 `*then begin 460 | print_endline (string_of_int i); 461 | loop (i+1) 462 | end in 463 | 464 | loop 0;; 465 | `e raise-error 466 | raise (Failure "bam!");; 467 | or 468 | 469 | failwith "bam!";; 470 | `e handle-error 471 | `*let x = `*try 1 / 0 `*with Division_by_zero -> 0;; 472 | `e type-of-exceptions 473 | exn 474 | `e user-defined-exception 475 | exception Foo `*of string;; 476 | 477 | raise (Foo "invalid input");; 478 | `e standard-exceptions 479 | Division_by_zero 480 | 481 | Failure string 482 | 483 | Not_found 484 | 485 | Invalid_argument string 486 | 487 | Match_failure (string, `.int, `.int) 488 | 489 | Assert_failure (string, `.int, `.int) 490 | 491 | Out_of_memory 492 | 493 | Stack_overflow 494 | `e assert 495 | assert(1 = 0);; 496 | `e standard-file-handles 497 | stdin stdout stderr 498 | `e read-line-from-stdin 499 | `*let line = read_line();; 500 | `e end-of-file-behavior 501 | raises End_of_file 502 | `e chomp 503 | 504 | `e write-line-to-stdout 505 | print_endline "lorem ipsum";; 506 | `e printf 507 | 508 | `e open-file-for-reading 509 | `*let f = open_in "/etc/passwd";; 510 | `e open-file-for-writing 511 | `*let f = open_out "/tmp/ocaml.out";; 512 | `e open-file-for-appending 513 | 514 | `e close-file 515 | 516 | `e i-o-errors 517 | 518 | `e read-line 519 | `*let ic = open_in "/etc/passwd" in 520 | 521 | `*let line = input_line ic in 522 | 523 | print_endline line;; 524 | `e iterate-over-file-by-line 525 | 526 | `e read-file-into-array-of-strings 527 | 528 | `e read-file-into-string 529 | 530 | `e write-string 531 | 532 | `e write-line 533 | open Printf 534 | 535 | `*let oc = open_out "/tmp/test-ocaml" in 536 | 537 | fprintf oc "hello out\n"; 538 | 539 | close_out oc;; 540 | `e flush-file-handle 541 | 542 | `e end-of-file-test 543 | 544 | `e get-and-set-file-handle-position 545 | 546 | `e file-exists-test-regular-test 547 | open Unix 548 | 549 | 550 | `*try `.Some (stat "/etc/hosts") `*with 551 | Unix_error (ENOENT, _, _) -> `.None 552 | 553 | 554 | (stat "/etc/hosts").st_kind = S_REG 555 | `e file-size 556 | (stat "/etc/hosts").st_size 557 | `e is-file-readable-writable-executable 558 | open Unix 559 | 560 | 561 | `*try access "/tmp/bar" [R_OK]; `=true `*with 562 | Unix.Unix_error (EACCES, _, _) -> `=false;; 563 | 564 | `*try access "/tmp/bar" [W_OK]; `=true `*with 565 | Unix.Unix_error (EACCES, _, _) -> `=false;; 566 | 567 | `*try access "/tmp/bar" [X_OK]; `=true `*with 568 | Unix.Unix_error (EACCES, _, _) -> `=false;; 569 | `e set-file-permissions 570 | open Unix 571 | 572 | 573 | chmod "/tmp/foo" 0o755 574 | `e copy-file-remove-file-rename-file 575 | open Unix 576 | 577 | ?? 578 | 579 | unlink "/tmp/foo" 580 | 581 | rename "/tmp/bar" "/tmp/foo" 582 | `e create-symlink-symlink-test-readlink 583 | open Unix 584 | 585 | 586 | symlink "/etc/hosts" "/tmp/hosts" 587 | 588 | (lstat "/tmp/hosts").st_kind = S_LNK 589 | 590 | readlink "/tmp/hosts" 591 | `e generate-unused-file-name 592 | open Filename 593 | 594 | (* prefix and suffix: *) 595 | 596 | temp_file "foo" ".txt" 597 | `e build-pathname 598 | open Filename 599 | 600 | 601 | concat "/etc" "hosts" 602 | `e dirname-and-basename 603 | open Filename 604 | 605 | 606 | dirname "/etc/hosts" 607 | 608 | basename "/etc/hosts" 609 | `e iterate-over-directory-by-file 610 | 611 | `e make-directory 612 | (* opam install fileutils *) 613 | 614 | open FileUtil 615 | 616 | 617 | mkdir ~parent:true "/tmp/foo/bar" 618 | `e remove-empty-directory 619 | open Unix 620 | 621 | 622 | rmdir "/tmp/foodir" 623 | `e remove-directory-and-contents 624 | 625 | `e directory-test 626 | 627 | `e system-temporary-file-directory 628 | 629 | `e command-line-arguments 630 | for i = 0 to Array.length Sys.argv - 1 do 631 | print_endline i Sys.argv.(i) 632 | 633 | done 634 | `e program-name 635 | 636 | `e getopt 637 | 638 | `e get-and-set-environment-variable 639 | open Unix 640 | 641 | 642 | s = getenv "HOME" 643 | 644 | putenv "PATH" "/bin" 645 | `e get-pid-parent-pid 646 | open Unix 647 | 648 | 649 | `*let pid = getpid() 650 | 651 | `*let ppid = getppid() 652 | `e get-user-id-and-name 653 | `*let uid = getuid() 654 | 655 | `*let username = 656 | (getpwuid (getuid())).pw_name 657 | `e exit 658 | exit 0 659 | 660 | 661 | exit 1 662 | `e set-signal-handler 663 | 664 | `e external-command 665 | 666 | `e escaped-external-command 667 | 668 | `e backticks 669 | 670 | `e namespace-example 671 | 672 | `e namespaces 673 | 674 | `e file-name-restrictions 675 | module Foo.Bar must be in Foo.ml 676 | `e namespace 677 | open Graphics;; 678 | `e namespace-creation 679 | put code in file MODULE_NAME.ml 680 | `e namespace-alias 681 | module Gr = Graphics;; 682 | `e namespace-separator 683 | . 684 | `e subnamespace 685 | in A.ml: 686 | 687 | module B = 688 | 689 | sig 690 | val display_instruction : unit -> unit 691 | 692 | end = 693 | 694 | struct 695 | `*let msg = "attack" 696 | `*let display_instruction () = print_endline msg 697 | 698 | end 699 | in client source: 700 | 701 | A.B.display_instruction;; 702 | `e package-manager-setup 703 | do this once: 704 | 705 | $ opam init 706 | 707 | for each shell session: 708 | 709 | $ eval $(opam config env) 710 | `e package-manager-search-install-list-installed 711 | $ opam search utop 712 | 713 | $ opam install utop 714 | 715 | $ opam list --installed 716 | `e compile-app-using-package 717 | 718 | `e type-synonym 719 | `*type name = string;; 720 | `e sum-type 721 | `*type color = Red | Green | Blue;; 722 | 723 | 724 | `*let col = Red;; 725 | 726 | (* evaluates to true: *) 727 | 728 | col < Green;; 729 | `e tuple-product-type-with-one-field 730 | `*type special_int = SpecialInt `*of `.int;; 731 | 732 | 733 | `*let n = SpecialInt 7;; 734 | `e tuple-product-type-with-two-fields 735 | `*type int_pair = IntPair `*of `.int * `.int;; 736 | 737 | 738 | `*let p = IntPair (7, 11);; 739 | `e record-product-type 740 | `*type customer = { 741 | id: `.int; 742 | name: string; 743 | address: string 744 | 745 | };; 746 | `e record-product-type-literal 747 | `*let cust = { 748 | id=7; 749 | name="John"; 750 | address="Topeka, KS" 751 | 752 | };; 753 | `e generic-type 754 | `*type ('a, 'b) twosome = 755 | Twosome `*of 'a * 'b;; 756 | 757 | 758 | `*let p = Twosome ("pi", 3.14);; 759 | `e recursive-type 760 | `*type binary_tree = 761 | | Leaf `*of `.int 762 | | Tree `*of binary_tree * binary_tree;; 763 | `e pattern-match-sum-type 764 | `*let col = Red;; 765 | 766 | 767 | `*let s = `*match col `*with 768 | | Red -> "red" 769 | | Blue -> "blue" 770 | | Green -> "green";; 771 | `e pattern-match-product-type 772 | 773 | `e pattern-match-guard 774 | `*match i `*with j `*when i < 0 -> -j | j -> j;; 775 | `e pattern-match-catchall 776 | `*let to_s c = `*match c `*with Red -> "red" | _ -> "not red";; 777 | 778 | to_s Green;; 779 | `e define-class 780 | class counter = object 781 | val mutable n = 0 782 | method incr = n <- n+1 783 | method get = n 784 | 785 | end;; 786 | `e create-object 787 | `*let c = new counter;; 788 | `e invoke-method 789 | c#incr;; 790 | 791 | c#get;; 792 | `e field-access 793 | none 794 | `e overload-function 795 | 796 | `e inheritance 797 | 798 | `e invoke-repl 799 | $ ocaml 800 | 801 | Use this if you want history: 802 | 803 | $ rlwrap ocaml 804 | 805 | The utop toplevel, which can be installed via opam, also provides history. 806 | `e repl-limitations 807 | 808 | `e repl-last-value 809 | none 810 | `e help 811 | none 812 | `e quit 813 | ^D 814 | `e inspect-type 815 | repl displays the type of any expression entered 816 | `e inspect-namespace 817 | module Unix = Unix;; 818 | `e load-source-file 819 | #use "hello";; 820 | `e load-package 821 | consider adding to .ocamlinit: 822 | 823 | #use "topfind";; 824 | 825 | # thread;; 826 | 827 | #require "core";; 828 | 829 | open Core.Std;; 830 | `e search-path 831 | #directory "libdir";; 832 | `e set-search-path-on-command-line 833 | ocaml -Ilibdir 834 | -------------------------------------------------------------------------------- /scala.txt: -------------------------------------------------------------------------------- 1 | `e versions-used 2 | 2.10 3 | `e show-version 4 | `$[scala -version] 5 | `e hello-world 6 | `c[script:] 7 | `.println(`=["Hello, world!"]) 8 | 9 | `c[object:] 10 | `*object Hello { 11 | `*def main(args: `.Array[`.String]) { 12 | `.println(`=["Hello, world!"]) 13 | } 14 | } 15 | 16 | `c[object, using App trait:] 17 | `*object Hello `*extends App { 18 | `.println(`=["Hello, world!"]) 19 | } 20 | `e file-suffixes 21 | .scala 22 | `c[none] 23 | .class 24 | `e interpreter 25 | `$[echo 'println("hello")' > hello.scala] 26 | `$[scala hello.scala] 27 | `e repl 28 | `$[scala] 29 | `e shebang 30 | `$[cat < hello.scala 31 | #!/bin/sh 32 | exec scala $0 $@ 33 | !# 34 | println("hello") 35 | EOF] 36 | 37 | `$[chmod +x hello.scala] 38 | `$[./hello.scala] 39 | `e bytecode-compiler-and-interpreter 40 | `$[cat < Hello.scala 41 | `*object Hello `*extends App { 42 | println("hello") 43 | } 44 | EOF] 45 | `$[scalac Hello.scala] 46 | `$[scala Hello] 47 | `e native-compiler 48 | `e library-which-is-always-imported 49 | java.lang 50 | scala 51 | `e statement-terminator 52 | ; or sometimes newline 53 | `e block-delimiters 54 | { } 55 | `e end-of-line-comment 56 | // comment 57 | `e multiple-line-comment 58 | /* comment 59 | another comment */ 60 | `e constant 61 | `c[evaluates 1 + 2 once:] 62 | `*val n = 1 + 2 63 | 64 | `c[evaluates 1 + 2 each time n is used:] 65 | `*def n = 1 + 2 66 | `e local-variable 67 | `*var n = 3 68 | n = 4 69 | n + 7 70 | `e unit-type-and-value 71 | `.Unit 72 | 73 | () 74 | `e assignment 75 | `*val v = 1 76 | `*var w = 0 77 | w = 1 `c[returns Unit] 78 | 79 | `c[assigns the same value to multiple variables; only works when variables are first defined:] 80 | `*val v1, v2 = 0 81 | `*var v3, v4 = 0 82 | `e parallel-assignment 83 | `c[only works when variables are first defined:] 84 | `*val (x, y, z) = (1, 2, 3) 85 | `e compound-assignment-arithmetic-string-logical-bit 86 | += -= *= /= `c[none] %= `c[none] 87 | += *= 88 | &= |= ^= 89 | <<= >>= &= |= ^= 90 | `e conditional-expression 91 | `*val n = -3 92 | 93 | `*if (n < 0) -n `*else n 94 | `e branch-type-mismatch 95 | `c[expression has type Any:] 96 | `*if (`=true) { "hello" } `*else { 3 } 97 | `e null 98 | `.None `c[type Option[T]] 99 | `=null `c[generally discouraged, but needed for Java interop] 100 | `e nullable-type 101 | `*val list = `.List(`.Some(3), `.None, `.Some(-4)) 102 | `e null-test 103 | v.isDefined `c[Option[T]] 104 | v eq `=null `c[Java null] 105 | `e coalesce 106 | `![throws Predef.NoSuchElementException if v is `.None:] 107 | v.get 108 | `c[0 if v is None:] 109 | v.getOrElse(0) 110 | `e nullif 111 | `e expression-type-declaration 112 | 1: `.Double 113 | `e let-in 114 | `*val z = { 115 | `*val x = 3.0 116 | `*val y = 2.0 * x 117 | x * y 118 | 119 | } 120 | `e where 121 | `e boolean-type 122 | Boolean 123 | `e true-and-false 124 | `=true `=false 125 | `e falsehoods 126 | `=false 127 | `e logical-operators 128 | && || ! 129 | `e relational-operators 130 | == != < > <= >= 131 | `e compare-strings 132 | == != < > <= >= 133 | `e min-and-max 134 | math.min 1 2 `c[or] 1 min 2 135 | math.max 1 2 `c[or] 1 max 2 136 | 137 | List(1, 2, 3).min 138 | List(1, 2, 3).max 139 | `e three-value-comparison 140 | `c[defined in scala.math.Ordered[A]:] 141 | 0 compare 1 142 | "do" compare "re" 143 | `e integer-type 144 | `.Int `c[type of integer literals] 145 | `.Byte `.Short `.Long `c[other modular types] 146 | `.BigInt `c[arbitrary precision type] 147 | `e integer-literal 148 | -4 149 | `e float-type 150 | `c[type of float literals:] 151 | `.Double 152 | 153 | `c[other types:] 154 | `.Float 155 | `e arithmetic-operators 156 | `++ `+- `+* `+/ `c[none] `+% 157 | `e integer-operators 158 | `++ `+- `+* `+/ `+% 159 | `e float-operators 160 | `++ `+- `+* `+/ 161 | `e add-integer-and-float 162 | 3 `++ 7.0 163 | `e integer-division 164 | 13 `+/ 5 165 | `e divmod 166 | 7 `+/ 3 167 | 7 `+% 3 168 | `c[BigInts only:] 169 | `.BigInt(7) `+[/%] `.BigInt(3) 170 | `e integer-division-by-zero 171 | `![java.lang.ArithmeticException] 172 | `e float-division 173 | 7.toDouble / 3 `c[type coercion built into Int] 174 | (7: `.Double) / 3 `c[type ascription, fueled by implicits] 175 | `e float-division-by-zero 176 | evaluates to Infinity, NaN, or -Infinity, values which do not have literals 177 | `e power 178 | math.pow(2, 32) 179 | `e sqrt 180 | math.sqrt(2) 181 | `e sqrt-1 182 | math.sqrt(-1) evaluates to NaN, a value which has no literal 183 | `e transcendental-functions 184 | math.exp math.log 185 | 186 | math.sin math.cos math.tan 187 | 188 | math.asin math.acos math.atan math.atan2 189 | `e transcendental-constants 190 | math.Pi 191 | 192 | math.E 193 | `e float-truncation 194 | 3.14.toInt `c[or] 3.14.toLong 195 | 3.14.round 196 | 3.14.floor `c[returns Double] 197 | 3.14.ceil `c[returns Double] 198 | `e absolute-value-and-signum 199 | math.abs(-7) 200 | math.signum(-7) 201 | `e integer-overflow 202 | modular arithmetic for all types except BigInt 203 | `e float-overflow 204 | evaluates to Infinity, a value which has no literal 205 | `e arbitrary-length-integer 206 | `*val n = BigInt(7) 207 | `*val m = BigInt(12) 208 | `e arbitrary-length-integer-operators 209 | n + m 210 | n - m 211 | n * m 212 | n / m 213 | n % m 214 | 215 | n == m 216 | n < m 217 | n < m 218 | n <= m 219 | n >= m 220 | `e rational-type 221 | 222 | `e rational-construction 223 | 224 | `e rational-decomposition 225 | 226 | `e complex-type 227 | 228 | `e complex-constants 229 | 230 | `e complex-operators 231 | 232 | `e complex-construction 233 | 234 | `e complex-decomposition 235 | 236 | `e random-number-uniform-integer-uniform-float-normal-float 237 | `*import scala.util.Random 238 | 239 | `*val rnd = Random 240 | 241 | rnd.nextInt(100) 242 | rnd.nextDouble 243 | rnd.nextGaussian 244 | `e random-seed 245 | `*import scala.util.Random 246 | 247 | `*val rnd = Random 248 | 249 | rnd.setSeed(17) 250 | `c[none] 251 | `c[none] 252 | `e bit-operators 253 | 1 << 4 254 | 1 >> 4 255 | 1 & 3 256 | 1 | 3 257 | 1 ^ 3 258 | ~ 1 259 | `e binary-octal-and-hex-literals 260 | `c[none] 261 | 052 262 | 0x2a 263 | `e radix-convert-integer-to-and-from-string-with-radix 264 | Integer.toString(42, 7) 265 | Integer.parseInt("60", 7) 266 | `e string-type 267 | java.lang.`.String `c[frequently implicitly converted to StringOps or WrappedString] 268 | `e string-literal 269 | `=["Hello, World!"] 270 | `=["""Hello, World!"""] 271 | `e newline-in-literal 272 | `c[in triple quote literal only] 273 | `=["""first line 274 | second line"""] 275 | `e literal-escapes 276 | `%[\b \f \n \r \t \" \' 277 | 278 | \uhhhh \o \oo \ooo] 279 | `e are-strings-mutable 280 | no 281 | `e format 282 | `=["foo `%[%s %d %.2f]"].format("bar", 7, 3.1415) 283 | `e concatenate-strings 284 | `=["Hello"] + `=[", "] + `=["World!"] 285 | `=["Hello"] ++ `=[", "] ++ `=["World!"] 286 | `e replicate-string 287 | `*val hbar = "-" * 80 288 | `e translate-case 289 | "hello".toUpperCase 290 | "HELLO".toLowerCase 291 | `e capitalize 292 | "hello".capitalize 293 | `e trim 294 | " hello ".trim 295 | `e pad 296 | ?? 297 | 298 | "hello".padTo(10, " ").mkString 299 | `e number-to-string 300 | "two: " + 2.toString 301 | "pi: " + 3.14.toString 302 | `e string-to-number 303 | 7 + "12".toInt 304 | 73.9 + ".037".toFloat 305 | `![raises NumberFormatException if string doesn't completely parse] 306 | `e join 307 | `.List("do", "re", "mi").mkString(" ") 308 | `e split 309 | "do re mi".split(" ") 310 | `e character-type 311 | `.Char 312 | `e character-literal 313 | `=['h'] 314 | `e test-character 315 | `=['c'].isLetter 316 | `=['c'].isDigit 317 | `=['c'].isSpaceChar 318 | `=['c'].isUpper 319 | `=['c'].isLower 320 | `e string-length 321 | "hello".length 322 | `e index-of-substring 323 | "hello".indexOf("hell") 324 | `e extract-substring 325 | "hello".substring(0, 4) 326 | `e extract-character 327 | "hello"(0) 328 | `e chr-and-ord 329 | `=['a'].toInt 330 | `=97.toChar 331 | `e to-array-of-characters 332 | `c[implicit --- via Predef.augmentString, to StringOps, or Predef.wrapString, to WrappedString] 333 | `e regex-type 334 | scala.util.matching.Regex 335 | `e literal-custom-delimited-literal 336 | `*val r = `=["lorem|ipsum"].r 337 | `c[none] 338 | `e character-class-abbreviations 339 | `%[. \c \s \S \d \D \w \W \x \O 340 | [:upper:] [:lower:] [:alpha:] [:alnum:] [:digit:] [:xdigit:] [:punct:] [:blank:] [:space:] [:cntrl:] [:graph:] [:print:] [:word:]] 341 | `e anchors 342 | `%[^ $ \A \b \B \< \> \Z] 343 | `e lookahead-positive-negative 344 | `%[(?= `c[...] ) 345 | (?! `c[...] ) 346 | (?<= `c[...] ) 347 | (?] { 362 | m.matched 363 | m.before 364 | m.after 365 | } 366 | `*case `.None `+[=>] ... `c[no match] 367 | } 368 | `e group-capture 369 | `*val rx = `=["""`%[(\d{4})]-`%[(\d{2})]-`%[(\d{2})]"""].r 370 | m = rx.findFirstMatchIn("2010-06-03") 371 | `*val `.List(yr, mo, dy) = m.get.subgroups 372 | 373 | `c[only full match:] 374 | `*val rx(yr, mo, dy) = "2010-06-03" 375 | `e named-group-capture 376 | `*val rx = "^(.+)\\.(.+)$".r("file", "suffix") 377 | `*val m = rx.findFirstMatchIn("foo.txt").get 378 | 379 | m.group("file") 380 | m.group("suffix") 381 | `e scan 382 | `*val s = "dolor sit amet" 383 | `*val ss: `.Iterator[`.String] = "\\w+".r.findAllIn('\w+', s) 384 | `*val ms: `.Iterator[Match] = "\\w+".r.findAllMatchIn('\w+', s) 385 | `e date-time-type 386 | 387 | `e current-date-time 388 | 389 | `e current-unix-epoch 390 | 391 | `e declare-on-heap 392 | `*val a: `.Array[`.Int] = `*new `.Array(10) 393 | `*val b = `.Array.fill(10)(0) 394 | 395 | `e array-initialization-list 396 | `*val a = `.Array(1, 2, 3) 397 | `e array-size 398 | a.length 399 | a.size `c[via implicit conversion to ArrayOps] 400 | `e array-lookup 401 | `*val n = a(0) 402 | `e array-update 403 | a(2) = 4 404 | `e array-out-of-bounds 405 | `![raises java.lang.ArrayIndexOutOfBounds] 406 | `e array-copy 407 | a.clone() 408 | `e array-iterate 409 | `*for (v `+[<-] a) { `c[code] } 410 | a.foreach(v `+[=>] `c[code] ) 411 | `e array-sort 412 | `.Array(3, 2, 1, 4).sorted 413 | `e list-name 414 | `.Seq `c[generic trait] 415 | `.List `c[immutable, preferred] 416 | `.ArrayBuffer, `.ListBuffer `c[mutable] 417 | `e list-literal 418 | `c[none; use constructor:] 419 | `.List(1, 2, 3) 420 | `e empty-list 421 | `.Nil 422 | `.List() 423 | `e empty-test 424 | `*val list = `.List(1, 2, 3) 425 | list == `.Nil 426 | list.isEmpty 427 | `e cons 428 | 1 :: `.List(2, 3) 429 | `e slice 430 | a.slice(2, 4) 431 | `e head 432 | `.List(1, 2, 3).head 433 | `e tail 434 | `.List(1, 2, 3).tail 435 | `e head-and-tail-of-empty-list 436 | `![NoSuchElementException:] 437 | `.Nil.head 438 | `![UnsupportedOperationException:] 439 | `.Nil.tail 440 | `e list-size 441 | `.List(1, 2, 3).length 442 | `.List(1, 2, 3).size 443 | `e capacity-get-increase 444 | `c[none] 445 | a.sizeHint(10) `c[ArrayBuffer, ListBuffer, or other Builder[Elem, To]] 446 | `e list-lookup 447 | `.List(1, 2, 3)(0) 448 | `e index-of-element 449 | `c[evaluates to 1:] 450 | `.List(7, 8, 9).indexOf(8) 451 | `c[evaluates to -1:] 452 | `.List(7, 8, 9).indexOf(10) 453 | `e list-update 454 | `c[evaluates to List(1, 4, 3]:) 455 | `.List(1, 2, 3).updated(1, 4) 456 | `e list-out-of-bounds 457 | `![raises `.[java.lang.IndexOutOfBoundsException]] 458 | `e concatenate-two-lists-list-of-lists 459 | `.List(1, 2) ::: `.List(3, 4) 460 | `.List(1, 2) ++ `.List(3, 4) 461 | `.List(`.List(1, 2), `.List(3, 4)).flatten 462 | `e list-replicate 463 | `*val a = List.fill(10)(None) 464 | `e last-and-butlast 465 | `.List(1, 2, 3).last 466 | `.List(1, 2, 3).init 467 | `e manipulate-back 468 | `*val a = ListBuffer(6, 7, 8) 469 | a.append(9) `c[or] a += 9 470 | 471 | a.remove(a.size - 1) `c[returns removed value] 472 | a.trimEnd(1) `c[does not return value] 473 | `e manipulate-front 474 | `*val a = ListBuffer(6, 7, 8) 475 | a.prepend(5) `c[or] 5 +=: a 476 | a.head 477 | a.remove(0) `c[returns removed value] 478 | a.trimStart(1) `c[does not return value] 479 | `e take 480 | `.List(1, 2, 3).take(2) 481 | `e drop 482 | `.List(1, 2, 3).drop(2) 483 | `e iterate-over-elements 484 | `.List(1, 2, 3).foreach(i `+[=>] println(i)) 485 | `e iterate-over-indices-and-elements 486 | `*val a = `.List("do", "re", "mi", "fa") 487 | `*for ((s, i) `+[<-] a.zipWithIndex) 488 | `.println("%s at index %d".format(s, i)) 489 | `e reverse 490 | `.List(1, 2, 3).reverse 491 | `e sort 492 | `.List(1, 3, 2, 4).sortWith((x, y) `+[=>] x < y) 493 | `.List(1, 3, 2, 4).sortWith(`+_ < `+_) 494 | `.List(1, 3, 2, 4).sortWith((x, y) `+[=>] x > y) 495 | `.List(1, 3, 2, 4).sortWith(`+_ > `+_) 496 | `e map 497 | `.List(1, 2, 3).map(x `+[=>] 2 * x) 498 | `.List(1, 2, 3).map(2 * `+_) 499 | `*for (x `+[<-] `.List(1, 2, 3)) `*yield 2 * x 500 | `e filter 501 | `.List(1, 2, 3).filter(x `+[=>] x > 2) 502 | `*for (x `+[<-] `.List(1, 2, 3); `*if x > 2) `*yield x 503 | `e fold-from-left 504 | `.List(1, 2, 3).foldLeft(0)(`+_ + `+_) 505 | `.List(1, 2, 3).foldLeft(0)((x, y) `+[=>] x + y) 506 | (0 /: `.List(1,2,3))(`+_ + `+_) 507 | `e fold-from-right 508 | `.List(1, 2, 3).foldRight(0)(`+_ - `+_) 509 | (`.List(1,2,3) :\ 0)(`+_ + `+_) 510 | `e membership 511 | `.List(1, 2, 3).contains(3) 512 | `e universal-test 513 | `.List(1, 2, 3).forall(`+_ > 2) 514 | `e existential-test 515 | `.List(1, 2, 3).exists(`+_ > 2) 516 | `e intersection 517 | `.List(1, 2) intersect `.List(2, 3, 4) `c[Sets also allow &] 518 | `e union 519 | `.List(1, 2) union `.List(2, 3, 4) `c[Sets also allow |] 520 | `e relative-complement-symmetric-difference 521 | `.List(1, 2) diff `.List(2, 3, 4) `c[Sets also allow &~] 522 | 523 | `c[only BitSets:] 524 | `*import scala.collection.BitSet 525 | BitSet(1, 2) ^ BitSet(2, 3, 4) 526 | `e min-and-max-element 527 | `.List(1,2,3).min 528 | `.List(1,2,3).max 529 | `e shuffle-and-sample 530 | `*import scala.util.Random 531 | Random.shuffle(`.List(1, 2, 3, 4)) 532 | `*new Random().shuffle(`.List(1, 2, 3, 4)) 533 | 534 | `c[none] 535 | `e zip 536 | List(1,2,3) zip List("a","b","c") 537 | (List(1,2,3), List("a","b","c")).zipped `c[allows mapping etc. with functions taking 2 arguments rather than a 2-tuple] 538 | `e iterate-over-range 539 | `c[includes 1000000:] 540 | `*for (i `+[<-] 1 to 1000000) { `c[code] } 541 | `c[excludes 1000000:] 542 | `*for (i `+[<-] 0 to 1000000) { `c[code] } 543 | `e instantiate-range-as-list 544 | `.List.range(1, 11) 545 | `e tuple 546 | (1, "hello", `=true) 547 | `e tuple-element-access 548 | (1, "hello", `=true)._1 549 | `e pair-element-access 550 | (12, "December")._1 551 | (12, "December")._2 552 | `e define-function 553 | `c[argument types must be declared:] 554 | `*def add3(x1: `.Int, x2: `.Int, x3: `.Int) 555 | = x1 + x2 + x3 556 | `*def average(a: `.Double, b: `.Double) 557 | = (a + b) / 2.0 558 | 559 | `c[return value type must be declared if function is recursive:] 560 | `*def factorial(n: `.Int): `.Int = 561 | `*if (n < 1) 562 | 1 563 | `*else 564 | n * factorial(n - 1) 565 | `e invoke-function 566 | `c[3.0:] 567 | average(1, 2 + 3) 568 | 569 | `c[4.5:] 570 | average(1, 2) + 3 571 | 572 | `c[parens can be omitted when a function takes no arguments, mainly for Java interopability; by convention parens are omitted when the function has no side effects] 573 | `e define-function-with-block-body 574 | `c[braces must be used if body not an expression:] 575 | `*def print_numbers() = { 576 | println("one") 577 | println("two") 578 | } 579 | `e apply-function-to-array 580 | `c[only for functions defined with variable number of arguments:] 581 | `*def firstAndLast(a: `.Int`+*) = { `c[...] } 582 | `*val a = List(1, 2, 3) 583 | firstAndLast(a:`+[_*]) 584 | `e variable-number-of-arguments 585 | `*def firstAndLast(a: `.Int`+*) = { 586 | `*if (a.length >= 1) `.println("first: " + a.head) 587 | `*if (a.length >= 2) `.println("last: " + a.last) 588 | } 589 | `e named-parameters 590 | `*def subtract(m: `.Int, s: `.Int) = m - s 591 | 592 | subtract(s = 3, m = 7) 593 | `e named-parameter-default-value 594 | `*def logarithm(x: `.Double, 595 | base: `.Double = math.exp(1)) = 596 | math.log(x) / math.log(base) 597 | 598 | logarithm(2.718) 599 | 600 | logarithm(10, base = 2) 601 | `e piecewise-defined-function 602 | `e recursive-function 603 | `*def range(a:`.Int, b:`.Int): `.List[`.Int] = 604 | `*if (a > b) 605 | `.List() 606 | `*else 607 | a :: range(a + 1, b) 608 | `e mutually-recursive-functions 609 | 610 | `e lambda 611 | (x: `.Double, y: `.Double) `+[=>] (x + y) / 2.0 612 | `e operator-as-function 613 | ((`+_:`.Int) * (`+_:w.Int))(3, 7) 614 | 615 | `c[implicit Numeric[T] make many math operations implicitly available] 616 | 617 | `c[Seqs are automatically functions sending an index to its corresponding element] 618 | `e overload-operator 619 | `c[almost all operators in Scala are just methods with symbolic names:] 620 | `*class Rational(`*val num: `.Int, `*val denom: `.Int) { 621 | `c[...] 622 | `*def +(o: Rational) 623 | = `*new Rational(num * o.denom + o.num * denom, denom * o.denom) 624 | } 625 | `e infix-operator-in-prefix-position 626 | `e function-in-infix-position 627 | unary methods can be used as binary operators 628 | `e currying 629 | `*def plus(x: `.Int)(y: `.Int) = x + y 630 | plus(3)(7) 631 | 632 | `c[must follow with underscore for partial application:] 633 | `*def plus2 = plus(2) `+_ 634 | plus2(7) 635 | `e composition 636 | `*val f = (x: `.Int) `+[=>] x + 2 637 | `*val g = (x: `.Int) `+[=>] x * 3 638 | (f compose g)(4) 639 | `e function-composition-operator 640 | `*val double = (x: `.Int) `+[=>] 2 * x 641 | `*val quadruple = double compose double 642 | 643 | `e lazy-evaluation 644 | `*def arg1(x: `+[=>] `.Int, y: `+[=>] `.Int): `.Int = x 645 | arg1(7, 1 / 0) 646 | `e strict-evaluation 647 | `c[default behavior] 648 | `e if 649 | `*if ( x > 0 ) 650 | println("pos") 651 | `e control-structure-keywords 652 | `*if (x > 0) 653 | println("pos") 654 | `*else `*if (x < 0) 655 | println("neg") 656 | `*else 657 | println("zero") 658 | `e sequencing 659 | println("one") 660 | println("two") 661 | println("three") 662 | `e while 663 | `*var i = 0 664 | `*while (i < 10) { 665 | printf("%d\n", i) 666 | i = i+1 667 | } 668 | `e for 669 | `*for (i `+[<-] 1 to 10) 670 | println(i) 671 | `e for-in-reverse 672 | `e list-iteration 673 | `*for (i `+[<-] `.List.range(1, 11).reverse) 674 | println(i) 675 | `e loop 676 | `e raise-exception 677 | `*throw `*new Exception("bam!") 678 | `e handle-exception 679 | `*import java.lang.`+_ 680 | 681 | `*val x = `*try { 682 | 1 / 0 683 | } `*catch { 684 | `*case e: ArithmeticException `+[=>] 0 685 | } 686 | `e type-of-exceptions 687 | 688 | `e user-defined-exception 689 | 690 | `e standard-exceptions 691 | 692 | `e assert 693 | assert(1 == 0) 694 | `e standard-file-handles 695 | System.in System.out System.err 696 | `e read-line-from-stdin 697 | `*val line = readLine() 698 | `e end-of-file-behavior 699 | 700 | `e chomp 701 | 702 | `e write-line-to-stdout 703 | println("lorem ipsum") 704 | `e printf 705 | 706 | `e open-file-for-reading 707 | `*import scala.io.Source 708 | 709 | `*val path = "/etc/hosts" 710 | `*val f = Source.fromFile(path) 711 | `e open-file-for-writing 712 | 713 | `e open-file-for-appending 714 | 715 | `e close-file 716 | `*import scala.io.Source 717 | 718 | f.close 719 | `e i-o-errors 720 | 721 | `e read-line 722 | `e iterate-over-file-by-line 723 | `*import scala.io.Source 724 | 725 | `*val src = Source.fromFile("/etc/passwd") 726 | `*for (line `+[<-] src.getLines) 727 | print(line) 728 | `e read-file-into-array-of-strings 729 | 730 | `e read-file-into-string 731 | 732 | `e write-string 733 | 734 | `e write-line 735 | `*val out = new java.io.FileWriter("/tmp/test-scala") 736 | out.write("hello out\n") 737 | out.close 738 | `e flush-file-handle 739 | 740 | `e end-of-file-test 741 | 742 | `e get-and-set-file-handle-position 743 | 744 | `e file-exists-test-regular-test 745 | 746 | `e file-size 747 | 748 | `e is-file-readable-writable-executable 749 | 750 | `e set-file-permissions 751 | 752 | `e copy-file-remove-file-rename-file 753 | 754 | `e create-symlink-symlink-test-readlink 755 | 756 | `e generate-unused-file-name 757 | 758 | `e build-pathname 759 | 760 | `e dirname-and-basename 761 | 762 | `e iterate-over-directory-by-file 763 | 764 | `e make-directory 765 | 766 | `e remove-empty-directory 767 | 768 | `e remove-directory-and-contents 769 | 770 | `e directory-test 771 | 772 | `e system-temporary-file-directory 773 | 774 | `e command-line-arguments 775 | `*object Test { 776 | `*def main(args: `.Array[`.String]) { 777 | `*for (arg `+[<-] args) 778 | println(arg) 779 | } 780 | } 781 | `e program-name 782 | 783 | `e getopt 784 | 785 | `e get-and-set-environment-variable 786 | 787 | `e get-pid-parent-pid 788 | 789 | `e get-user-id-and-name 790 | 791 | `e exit 792 | 793 | `e set-signal-handler 794 | 795 | `e external-command 796 | 797 | `e escaped-external-command 798 | 799 | `e backticks 800 | 801 | `e namespace-example 802 | `c[Baz.scala] 803 | package Foo.Bar; 804 | 805 | 806 | `*class Baz { 807 | `*def say() { println("hello"); } 808 | } 809 | 810 | `c[Main.scala] 811 | `*import Foo.Bar.Baz; 812 | 813 | `*object Main { 814 | `*def main(args : `.Array[`.String]) { 815 | `*val baz = new Baz; 816 | baz.say(); 817 | } 818 | } 819 | 820 | to compile and run 821 | 822 | `$[scalac Baz.scala] 823 | `$[scalac Main.scala] 824 | `$[scala Main] 825 | hello 826 | `e namespaces 827 | 828 | `e file-name-restrictions 829 | `c[none] 830 | `e namespace 831 | 832 | `e namespace-creation 833 | 834 | `e namespace-alias 835 | 836 | `e namespace-separator 837 | 838 | `e subnamespace 839 | 840 | `e package-manager-setup 841 | 842 | `e package-manager-search-install-list-installed 843 | 844 | `e compile-app-using-package 845 | 846 | `e type-synonym 847 | type Name = `.String 848 | `e sum-type 849 | `*abstract `*class Color 850 | `*case `*object Red `=extends Color 851 | `*case `*object Blue `=extends Color 852 | `*case `*object Green `=extends Color 853 | 854 | `*val col = Red 855 | 856 | `c[this won’t compile:] 857 | col < Green 858 | `e tuple-product-type-with-one-field 859 | `*class SpecialInt(x: `.Int) 860 | `*val n = new SpecialInt(7) 861 | `e tuple-product-type-with-two-fields 862 | `*class IntPair(a: `.Int, b: `.Int) 863 | `*val p = new IntPair(7, 11) 864 | `e record-product-type 865 | `*case `*class Customer( 866 | id: `.Int, 867 | name: `.String, 868 | address: `.String 869 | ) 870 | `e record-product-type-literal 871 | Customer(7,"John","Topeka, KS") 872 | Customer(id=7, name="John", address="Topeka, KS") 873 | `e generic-type 874 | `*class Twosome[A, B](a: A, b: B) 875 | 876 | `*val p = new Twosome("pi", 3.14) 877 | `e recursive-type 878 | `*abstract `*class BinaryTree 879 | 880 | `*case `*class Tree(left: BinaryTree, right: BinaryTree) `=extends BinaryTree 881 | `*case `*class Leaf(x: `.Int) `=extends BinaryTree 882 | `e pattern-match-sum-type 883 | `*val c:Color = Red; 884 | 885 | c `*match { `*case Red `+[=>] "red"; `*case Green `+[=>] "green"; `*case Blue `+[=>] "blue" } 886 | `e pattern-match-product-type 887 | 888 | `e pattern-match-guard 889 | `*match { `*case i: `.Int `*if i < 0 `+[=>] - i; `*case i: `.Int `+[=>] i } 890 | `e pattern-match-catchall 891 | `*val c : Color = Green 892 | 893 | c `*match { `*case Red `+[=>] "red"; `*case `+_ `+[=>] "not red" } 894 | `e define-class 895 | `*class Counter { 896 | `*private `*var n = 0 897 | `*def incr(): `.Unit = { n = n+1 } 898 | `*def get(): `.Int = { n } 899 | } 900 | `e create-object 901 | `*val c = `*new Counter 902 | `e invoke-method 903 | c.incr 904 | c.get 905 | `e field-access 906 | 907 | `e overload-function 908 | 909 | `e inheritance 910 | 911 | `e invoke-repl 912 | `$[scala] 913 | `e repl-limitations 914 | `e repl-last-value 915 | res0, res1, … 916 | `e help 917 | :help 918 | `e quit 919 | 920 | `e inspect-type 921 | repl displays the type of any expression entered 922 | `e inspect-namespace 923 | 924 | `e load-source-file 925 | 926 | `e load-package 927 | 928 | `e search-path 929 | 930 | `e set-search-path-on-command-line 931 | 932 | -------------------------------------------------------------------------------- /tcl.txt: -------------------------------------------------------------------------------- 1 | `e version-used 2 | 8.5 3 | `e show-version 4 | $ tclsh 5 | 6 | % info tclversion 7 | `e interpreter 8 | $ tclsh foo.tcl 9 | `e repl 10 | $ tclsh 11 | `e command-line-program 12 | none 13 | `e block-delimiters 14 | {} or "" 15 | `e statement-terminator 16 | newline or ; 17 | 18 | newline not a separator inside {}, "", [] or after backslash: \ 19 | `e are-expressions-statements 20 | no 21 | `e end-of-line-comment 22 | # comment 23 | `e multiple-line-comment 24 | if (0) { 25 | commented out 26 | can contain {} if balanced 27 | 28 | } 29 | `e local-variable 30 | # set variable inside procedure 31 | proc foo {args} { 32 | set x 1 33 | … 34 | 35 | } 36 | `e global-variable 37 | # set variable outside procedure 38 | set g 1 39 | 40 | proc incr_global {} { 41 | global g 42 | incr g 43 | 44 | } 45 | `e assignment 46 | set x 1 47 | `e parallel-assignment 48 | lassign {1 2 3} x y z 49 | 50 | # 3 is discarded: 51 | 52 | lassign {1 2 3} x y 53 | 54 | # z is set to "": 55 | 56 | lassign {1 2} x y z 57 | `e swap 58 | lassign "$x $y" y x 59 | `e null 60 | "" 61 | `e null-test 62 | v eq "" 63 | `e uninitialized-local-variable 64 | error 65 | `e uninitialized-global-variable 66 | error 67 | `e conditional-expression 68 | expr $x > 0 ? $x : -$x 69 | `e true-and-false 70 | 1 0 71 | `e falsehoods 72 | 0 "false" "no" 73 | most strings cause error in boolean context; nonzero numbers are true 74 | `e logical-operators 75 | && || ! 76 | `e relational-expression 77 | if {$x > 3} {…} 78 | # outside of conditionals use expr: 79 | expr $x > 3 80 | `e relational-operators 81 | == != > < >= <= 82 | 83 | # string comparison: 84 | 85 | eq ne 86 | `e min-and-max 87 | expr min(1, 2, 3) 88 | expr max(1, 2, 3) 89 | `e arithmetic-expression 90 | expr 1 + 3 91 | # expr not needed in conditionals: 92 | if {1 + 3} {…} 93 | `e arithmetic-operators-addition-subtraction-multiplication-float-division-quotient-modulus 94 | + - * none / % 95 | `e integer-division 96 | expr $x / $y 97 | `e integer-division-by-zero 98 | error 99 | `e float-division 100 | expr $x * 1.0 / $y 101 | `e float-division-by-zero 102 | returns assignable value Inf if dividend is positive and -Inf if negative. Raises error if dividend is zero. 103 | 104 | 105 | There is a literal for Inf. 106 | `e power 107 | expr 2 ** 32 108 | expr pow(2, 32) 109 | `e sqrt 110 | expr sqrt(2) 111 | `e sqrt-1 112 | error 113 | `e transcendental-functions 114 | exp log sin cos tan asin acos atan atan2 115 | # how to use math functions: 116 | expr exp(2) 117 | expr atan2(1, 1) 118 | 119 | ::tcl::mathfunc::exp 2 120 | 121 | ::tcl::mathfunc::atan2 1 1 122 | `e transcendental-constants 123 | expr 4 * atan(1) 124 | expr exp(1) 125 | `e float-truncation 126 | expr int(3.1) 127 | expr round(3.1) 128 | expr floor(3.1) 129 | expr ceil(3.1) 130 | `e absolute-value-and-signum 131 | expr abs(-3) 132 | `e integer-overflow 133 | arbitrary length integers introduced in 8.5 134 | `e float-overflow 135 | error 136 | `e random-number-uniform-integer-uniform-float-normal-float 137 | expr int(rand() * 100) 138 | expr rand() 139 | none 140 | `e random-seed 141 | expr srand(17) 142 | `e bit-operators 143 | << >> & | ^ ~ 144 | `e string-literal 145 | "don't say \"no\"" 146 | 147 | {don't say "no"} 148 | `e newline-in-literal 149 | yes 150 | `e literal-escapes 151 | in double quotes: 152 | 153 | \a \b \f \n \r \t \v \\ \" \oooo \uhhhh \xhh 154 | `e variable-interpolation 155 | set count 3 156 | set item "ball" 157 | "$count ${item}s" 158 | `e expression-interpolation 159 | none 160 | `e concatenate-strings 161 | set s1 "Hello, " 162 | set s2 "World!" 163 | set s $s1$s2 164 | `e split 165 | split "do re mi" 166 | `e join 167 | join [list "do" "re" "mi"] " " 168 | `e format 169 | set fmt "lorem %s %d %.2f" 170 | format $fmt "ipsum" 13 3.7 171 | `e translate-case 172 | string toupper "lorem" 173 | string tolower "LOREM" 174 | none 175 | `e strip 176 | string trim " lorem " 177 | string trimleft " lorem" 178 | string trimright "lorem " 179 | `e pad 180 | format "%10s" "lorem" 181 | format "%-10s" "lorem" 182 | `e string-to-number 183 | use expr to interpret as numbers: 184 | set x "12" 185 | expr 7 + $x 186 | set y ".037" 187 | expr 73.9 + $y 188 | `e number-to-string 189 | all values are strings 190 | `e string-length 191 | string length "lorem" 192 | `e index-of-substring 193 | string first "ipsum" "lorem ipsum" 194 | `e extract-substring 195 | string range "lorem ipsum" 6 10 196 | `e chr-and-ord 197 | format %c 65 198 | scan A %c ascii_value 199 | `e character-class-abbreviations-and-anchors 200 | char class abbrevs: 201 | 202 | . \d \D \s \S \w \W 203 | 204 | anchors: ^ $ \A \m \M \y \Y \Z 205 | `e match-test 206 | if [regexp -- {1999} $s] { 207 | puts "party!" 208 | 209 | } 210 | `e case-insensitive-match-test 211 | regexp -nocase -- {lorem} "Lorem" 212 | `e modifiers 213 | -all -expanded -indices -inline 214 | 215 | -line -lineanchor -linestop -nocase 216 | `e substitution 217 | set s "do re mi mi mi" 218 | regsub -all -- "mi" $s "ma" 219 | `e group-capture 220 | set s "2009-06-03" 221 | set rx {^(\d{4})-(\d{2})-(\d{2})$} 222 | regexp -- $rx $s - yr mo dy 223 | `e backreference-in-match-and-substitution 224 | regexp -- {(\w+) \1} "do do" 225 | 226 | set rx {(\w+) (\w+)} 227 | regsub -all -- $rx "do re" {\2 \1} 228 | `e current-date-time 229 | set t [clock seconds] 230 | `e to-unix-epoch-from-unix-epoch 231 | t 232 | set t2 1315716177 233 | `e strftime 234 | set fmt "%Y-%m-%d %H:%M:%S" 235 | clock format $t -format $fmt 236 | `e strptime 237 | none 238 | `e parse-date-w-o-format 239 | set t [clock scan "July 7, 1999"] 240 | `e date-parts 241 | clock format $t -format "%Y" 242 | clock format $t -format "%m" 243 | clock format $t -format "%d" 244 | `e time-parts 245 | clock format $t -format "%H" 246 | clock format $t -format "%M" 247 | clock format $t -format "%S" 248 | `e build-date-time-from-parts 249 | none 250 | `e sleep 251 | after 500 252 | `e list-name 253 | list 254 | `e list-literal 255 | set a [list 1 2 3 4] 256 | set a {1 2 3 4} 257 | `e list-size 258 | llength $a 259 | `e list-lookup 260 | lindex $a 0 261 | `e list-update 262 | # provide start and end index 263 | 264 | # of elements to replace: 265 | set a [lreplace $a 1 1 "lorem"] 266 | `e out-of-bounds 267 | returns "" 268 | `e index-of-element 269 | lsearch {6 7 7 8} 7 270 | lindex [lsearch -all {6 7 7 8} 7] end 271 | # returns -1 if not found 272 | `e slice 273 | lrange $a 1 2 274 | `e drop 275 | lrange {"a" "b" "c" "d"} 1 end 276 | `e concatenate 277 | set a [concat {1 2 3} {4 5 6}] 278 | `e list-replicate 279 | lrepeat 10 "" 280 | `e manipulate-back 281 | set a {6 7 8} 282 | lappend a 9 283 | set i [lindex $a end] 284 | set a [lreplace $a end end] 285 | `e manipulate-front 286 | set a {6 7 8} 287 | set a [concat {5} $a] 288 | set a [lassign $a i] 289 | `e iterate-over-elements 290 | foreach i $a { puts $i } 291 | `e reverse 292 | set a {1 2 3} 293 | set a [lreverse $a] 294 | `e sort 295 | set a {3 1 4 2} 296 | set a [lsort $a] 297 | `e dedupe 298 | lsort -unique {1 2 2 3} 299 | `e membership 300 | expr {7 in $a} 301 | expr {7 ni $a} 302 | `e intersection 303 | package require struct::set 304 | 305 | 306 | ::struct::set intersect {1 2} {2 3} 307 | `e union 308 | package require struct::set 309 | 310 | 311 | ::struct::set union {1 2} {2 3 4} 312 | `e relative-complement-symmetric-difference 313 | package require struct::set 314 | 315 | 316 | ::struct::set difference {1 2 3} {2} 317 | `e map 318 | package require struct::list 319 | 320 | proc sqr {x} {return [expr $x * $x]} 321 | 322 | ::struct::list map {1 2 3} sqr 323 | `e filter 324 | package require struct::list 325 | 326 | proc gt1 {x} {return [expr $x > 1]} 327 | 328 | ::struct::list filter {1 2 3} gt1 329 | `e fold-from-left 330 | package require struct::list 331 | 332 | 333 | ::struct::list fold {1 2 3} 0 334 | ::tcl::mathop::+ 335 | `e shuffle-and-sample 336 | none 337 | `e zip 338 | none 339 | `e map-literal 340 | set d [dict create t 1 f 0] 341 | `e map-size 342 | dict size $d 343 | `e map-lookup 344 | dict get $d t 345 | `e map-update 346 | dict set d t 2 347 | `e map-out-of-bounds 348 | error 349 | `e is-key-present 350 | dict exists $d t 351 | `e delete 352 | dict unset d t 353 | `e iteration 354 | foreach {k v} $d { 355 | code 356 | 357 | } 358 | `e declare-function 359 | proc add { x y } { 360 | expr $x + $y 361 | 362 | } 363 | `e invoke-function 364 | add 1 2 365 | `e missing-argument-behavior 366 | error 367 | `e extra-arguments 368 | error 369 | `e default-value 370 | proc log {x {base 10 }} { body } 371 | `e variable-number-of-arguments 372 | last arg contains list of remaining values 373 | `e return-value 374 | return arg or empty string 375 | `e multiple-return-values 376 | none 377 | `e lambda 378 | set sqr {{x} {return [expr $x*$x]}} 379 | `e lambda-invocation 380 | apply $sqr 2 381 | `e default-scope 382 | local 383 | `e nested-function-visibility 384 | not visible outside containing function 385 | `e if 386 | if { 0 == $n } { 387 | puts "no hits" 388 | 389 | } elseif { 1 == $n } { 390 | puts "1 hit" 391 | 392 | } else { 393 | puts "$n hits" 394 | 395 | } 396 | `e while 397 | while { $i < 100 } { 398 | incr i 399 | 400 | } 401 | `e break-continue-redo 402 | break continue 403 | `e for 404 | for {set i 0} {$i < 10} {incr i} { 405 | puts $i 406 | 407 | } 408 | `e raise-exception 409 | error "bad arg" 410 | `e catch-exception 411 | catch risky retval 412 | if { retval != 0 } { 413 | puts "risky failed" 414 | 415 | } 416 | `e finally 417 | none 418 | `e uncaught-exception-behavior 419 | stderr and exit 420 | `e generator 421 | to be added to Tcl 8.6 422 | `e standard-file-handles 423 | stdin 424 | 425 | stdout 426 | 427 | stderr 428 | `e read-line-from-stdin 429 | gets stdin line 430 | `e write-line-to-stdout 431 | puts "Hello, World!" 432 | `e open-file-for-reading 433 | set f [open "/tmp/foo"] 434 | `e open-file-for-writing 435 | set f [open "/tmp/foo" "w"] 436 | `e close-file 437 | close $f 438 | `e read-line 439 | gets $f 440 | `e iterate-over-file-by-line 441 | while { [gets $f s] >= 0 } { 442 | use s 443 | 444 | } 445 | `e chomp 446 | string trimright $line "\r\n" 447 | `e read-file 448 | read $f 449 | `e write-to-file 450 | puts -nonewline $f "lorem ipsum" 451 | `e flush-file-handle 452 | flush $f 453 | `e file-exists-test-regular-test 454 | file exists "/etc/hosts" 455 | file isfile "/etc/hosts" 456 | `e file-size 457 | 458 | `e is-file-readable-writable-executable 459 | 460 | `e copy-file-remove-file-rename-file 461 | file copy "/tmp/foo" "/tmp/bar" 462 | file delete "/tmp/foo" 463 | file rename "/tmp/bar" "/tmp/foo" 464 | `e set-file-permissions 465 | set s "/tmp/foo" 466 | file attributes $s -permissions 0755 467 | `e temporary-file 468 | set tmp [::fileutil::tempfile foo] 469 | set f [open $tmp "w"] 470 | puts $f "lorem ipsum" 471 | close $f 472 | puts "tmp file: $tmp" 473 | `e build-pathname 474 | file join "/etc" "hosts" 475 | `e dirname-and-basename 476 | file dirname "/etc/hosts" 477 | 478 | file tail "/etc/hosts" 479 | `e iterate-over-directory-by-file 480 | 481 | `e make-directory 482 | file mkdir "/tmp/foo/bar" 483 | `e remove-empty-directory 484 | file delete "/tmp/foodir" 485 | `e remove-directory-and-contents 486 | file delete -force "/tmp/foodir" 487 | `e directory-test 488 | file isdirectory "/tmp" 489 | `e command-line-arguments 490 | [lindex $argv 0] 491 | 492 | [lindex $argv 1] 493 | … 494 | `e environment-variable 495 | $env(HOME) 496 | `e exit 497 | exit 0 498 | `e external-command 499 | exec ls 500 | `e backticks 501 | set f [ open |ls ] 502 | 503 | read f 504 | `e library 505 | $ cat foo.tcl 506 | 507 | proc add {x y} {expr $x + $y} 508 | `e import-library 509 | source foo.tcl 510 | 511 | add 3 7 512 | `e library-path 513 | none 514 | `e library-path-environment-variable 515 | TCLLIBPATH 516 | `e declare-namespace 517 | namespace 518 | `e namespace-separator 519 | :: 520 | `e list-installed-packaged-install-a-package 521 | 522 | `e define-class 523 | 524 | `e create-object 525 | 526 | `e create-blank-object 527 | 528 | `e set-attribute 529 | 530 | `e get-attribute 531 | 532 | `e define-method 533 | 534 | `e invoke-method 535 | 536 | `e clone-object 537 | 538 | `e object-literal 539 | 540 | `e inspect-type 541 | 542 | `e has-method 543 | 544 | `e message-passing 545 | 546 | `e eval 547 | 548 | `e inspect-methods 549 | 550 | `e inspect-attributes 551 | 552 | --------------------------------------------------------------------------------