-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathllms-cortex.txt
More file actions
8299 lines (6425 loc) · 267 KB
/
Copy pathllms-cortex.txt
File metadata and controls
8299 lines (6425 loc) · 267 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Epsil — complete documentation
# Epsil
Source: https://epsil.dev/introduction/
# Epsil
<Intro>
A programming language for scientific computing
</Intro>
:::warning[Experimental]
Epsil is still being developed. Its syntax and semantics may change between
releases while the language is being exercised by early adopters. Your feedback
can help shape its direction.
:::
Epsil is embedded from JavaScript through the
`@cortex-js/compute-engine/epsil` entry point:
```js
import { ComputeEngine, executeEpsil } from "@cortex-js/compute-engine/epsil";
const ce = new ComputeEngine();
const { value, diagnostics } = executeEpsil(ce, "1 + 2");
```
Here is "Hello World" in Epsil. Edit the code and press **Run** (or
<kbd>⌘/Ctrl</kbd>+<kbd>Enter</kbd>) — the result is the value of the last
statement.
```epsil-live
"Hello World"
```
Epsil is **symbolic by default**: expressions stay exact unless you ask for a
numeric approximation with `N()`.
```epsil-live
Simplify(2 + 3x^3 + 2x^2 + x^3 + 1)
```
Values have a type, and strings support `\(…)` interpolation:
```epsil-live
let x = 2^11 - 1
"\(x) has type \(Type(x))"
```
Errors are ordinary values, so a program never throws to its host — a problem
surfaces as an `Error` value or a diagnostic:
```epsil-live
const answer = 42
answer = 0
```
## Guide
The guide explains the language through examples and decisions: not only what
syntax means, but when a form is useful and why you might choose it.
<ReadMore path="/tour/">
Take **A Tour of Epsil** — a one-page, example-led introduction to exact
math, functions, collections, control flow, and types.
</ReadMore>
<ReadMore path="/getting-started/">
Follow **Getting Started** — install Epsil, try the REPL, run a source file,
and embed the language in JavaScript.
</ReadMore>
<ReadMore path="/examples/">
Explore **complete Epsil programs** for symbolic computation, collections,
calculus, linear algebra, strings, and more.
</ReadMore>
<ReadMore path="/cli/">
Use the **CLI and interactive REPL** from a terminal.
</ReadMore>
<ReadMore path="/from-python/">
Coming from **Python**? Translate your idioms — and learn the three reflexes
that silently do the wrong thing.
</ReadMore>
<ReadMore path="/from-mathematica/">
Coming from **Mathematica**? Most of the mental model carries over; here is
what changes.
</ReadMore>
<ReadMore path="/evaluation/">
Understand **how Epsil evaluates** — exact values, mutable bindings, lazy
collections, ordinary error values, and session scope.
</ReadMore>
## Tools and Integrations
<ReadMore path="/for-agents/">
Writing Epsil with an LLM? Give it the **language card for AI agents** — a
condensed, machine-verified reference.
</ReadMore>
<ReadMore path="/mcp/">
Connect ChatGPT, Claude, or another AI assistant to Epsil with the built-in
**MCP server** — exact math as a tool call.
</ReadMore>
## Language Reference
The reference is organized by language feature. Use it when you know what you
are looking for and need the complete rule, grammar, or edge case.
<ReadMore path="/syntax/">
Read more about the **formal syntax of Epsil** — statements, primaries,
calls and indexing.
</ReadMore>
<ReadMore path="/literals/">
**Literals** — numbers, strings, symbols, and `$…$` LaTeX islands.
</ReadMore>
<ReadMore path="/operators/">
**Operators** — arithmetic, logic, relational, and the pipeline operator.
</ReadMore>
<ReadMore path="/control-flow/">
**Control flow** — `if`/`else`, `match`, loops, blocks, and functions.
</ReadMore>
<ReadMore path="/declarations/">
**Declarations** — names, `let`, `const`, destructuring, function-type
annotations that bind their parameters, scopes, and named types.
</ReadMore>
<ReadMore path="/types/">
**Types** — annotations, named types, effects, and absence values.
</ReadMore>
<ReadMore path="/protocols/">
**Protocols** — declaring operation sets, conforming types to them, and
dispatching on the receiver.
</ReadMore>
<ReadMore path="/comments/">
**Comments** — line and block comments.
</ReadMore>
<ReadMore path="/pragmas/">
**Pragmas** — parser directives embedded in the code.
</ReadMore>
<ReadMore path="/implementation/">
**Inside Epsil** — the JavaScript API, and the MathJSON each language form
lowers to. Not needed to write Epsil.
</ReadMore>
## Collections
Epsil has literal syntax for lists and dictionaries.
**Lists** are ordered and 1-indexed with `xs[i]`:
```epsil-live
[3, 5, 7, 11]
```
**Dictionaries** are sets of key/value pairs. The empty dictionary is `{->}`:
```epsil-live
{one -> 1, two -> 2}
```
<ReadMore path="/syntax/#collections-tuples-and-dictionaries">
Read more about **lists, sets, tuples and dictionaries**.
</ReadMore>
## Future Directions
Several keywords are **reserved but not designed** — they are held so that a
future version of Epsil can introduce them without breaking existing programs,
and using one as an ordinary name today is an error. None of the following are
part of the language yet:
- **Modules and imports** — `import`, `export`, `module`.
- **Error-handling keywords** — `try`, `catch`, `throw`. In Epsil, errors are
ordinary values, so these are not needed for the current design.
- **Concurrency** — `async`, `await`, `parallel`.
- **Macros** and compile-time metaprogramming.
If you need a symbol whose name collides with one of these reserved words, use
the verbatim form (`` `match` ``).
---
# Getting Started with Epsil
Source: https://epsil.dev/getting-started/
# Getting Started
<Intro>
Install Epsil and run your first symbolic program in five minutes.
</Intro>
:::warning[Experimental]
Epsil is experimental. Its syntax and behavior may change between releases.
:::
## Install
Epsil is included with the Compute Engine package:
```shell
npm install @cortex-js/compute-engine
```
The package installs an `epsil` command. During development, run the
project-local command through `npx`.
## Try the REPL
Start an interactive session:
```shell
npx epsil
```
Enter a declaration, then use it in another expression:
```text
epsil> let x = 5
5
epsil> x^2
25
```
The REPL keeps declarations and assignments between inputs. Enter `.help` for
the available commands and `.exit` when you are done.
## Run a Source File
Save this program as `squares.epsil`:
```epsil
square(x) = x^2
Map(square, 1..5)
```
Run it:
```shell
npx epsil squares.epsil
```
The result is:
```text
[1,4,9,16,25]
```
The conventional file extension is `.epsil`.
## Work Symbolically
Expressions remain exact and symbolic by default:
```epsil-live
Simplify(2 + 3x^3 + 2x^2 + x^3 + 1)
```
Use `N()` when you want a numeric approximation:
```epsil-live
N(Sqrt(2))
```
## Embed Epsil in JavaScript
Import the experimental Epsil entry point, create a `ComputeEngine`, then
execute source text:
```js
import {
ComputeEngine,
executeEpsil,
} from "@cortex-js/compute-engine/epsil";
const ce = new ComputeEngine();
const { value, diagnostics } = executeEpsil(
ce,
"factorial(n) = 1 if n <= 1 else n * factorial(n - 1)\nfactorial(10)"
);
if (diagnostics.length > 0) console.error(diagnostics);
console.log(value.toString()); // 3628800
```
Calls made with the same `ComputeEngine` share its top-level declarations,
which is useful for notebook cells and other stateful sessions. Create a fresh
engine when you want an isolated program.
## Where to Go Next
<ReadMore path="/tour/">
Read **A Tour of Epsil** for a compact, example-led introduction to the
language before diving into individual features.
</ReadMore>
<ReadMore path="/examples/">
Study **complete programs** covering control flow, collections, symbolic
calculus, linear algebra, strings, and reproducible randomness.
</ReadMore>
<ReadMore path="/cli/">
Learn the **CLI and REPL** commands, output modes, diagnostics, and evaluation
limits.
</ReadMore>
<ReadMore path="/syntax/">
Use the **language reference** for syntax, operators, declarations, types, and
control flow.
</ReadMore>
<ReadMore path="/from-python/">
Already know **Python**? Start from the idiom-by-idiom translation guide.
</ReadMore>
<ReadMore path="/from-mathematica/">
Already know **Mathematica**? Start from the Wolfram Language translation
guide.
</ReadMore>
---
# A Tour of Epsil
Source: https://epsil.dev/tour/
# A Tour of Epsil
<Intro>
In one page, write and read the Epsil programs you will use most often.
</Intro>
Epsil is a language for scientific computing built on the Compute Engine. Its
most useful starting idea is that mathematical expressions retain their meaning:
they stay exact and symbolic until you explicitly ask for an approximation.
This tour is deliberately quick. It introduces the language through complete,
executable snippets and points to the guide when a feature deserves a deeper
explanation.
## Exact mathematics, when it matters
Ordinary arithmetic is exact. `1 / 3` is the rational number one third, not a
rounded floating-point value; symbolic expressions also remain available for
later manipulation:
```epsil
let share = 1 / 3
Simplify(share + share + share)
// ➔ 1
```
This is valuable when a formula needs to be transformed, compared, or carried
through several steps without accumulating rounding error. Use `N()` at the
point where a decimal is actually useful — for presentation, plotting, or a
numerical algorithm:
```epsil
N(Sqrt(2))
// ➔ 1.4142135623730951
```
Capitalized names such as `Simplify`, `Sqrt`, and `N` are Compute Engine
operators. Lowercase names are normally the names you introduce.
## Names describe values
Use `let` for a name whose value will change, and `const` for one that should
not. Values themselves are immutable; `let` makes the *binding* movable.
```epsil
const secondsPerMinute = 60
let elapsed = 2
elapsed = elapsed + 1
elapsed * secondsPerMinute
// ➔ 180
```
That distinction makes it clear which programs are stateful. A collection is
never changed in place: an operation creates a new value, and you can choose
whether to bind it to a new name or replace an old binding.
```epsil
let readings = [3, 1, 2]
let sorted = Sort(readings)
(readings, sorted)
// ➔ ([3, 1, 2], [1, 2, 3])
```
Read [Declarations](/declarations/) for scopes, destructuring, and type
annotations; [Evaluation](/evaluation/) explains the value-and-binding
model in depth.
## Functions read like formulas
For a one-line mathematical definition, put parameters in parentheses and the
formula after `=`:
```epsil
circleArea(r) = Pi * r^2
circleArea(3)
// ➔ 9π
```
For a function with local names or several steps, use a block. The last
expression is the result, so there is no `return` ceremony:
```epsil
function hypotenuse(a, b) {
let squared = a^2 + b^2
Sqrt(squared)
}
hypotenuse(3, 4)
// ➔ 5
```
Anonymous functions use `|->`. They are especially useful for a small
transformation passed to a collection operator:
```epsil
Map(n |-> n^2, 1..5)
// ➔ [1, 4, 9, 16, 25]
```
Use a named function when its name explains the operation or the body needs
room to grow; use a lambda when the transformation is local and obvious. More
forms, including recursion and multiple clauses, are in
[Control Flow](/control-flow/#functions).
## Branches produce values
`if` is an expression, not merely a way to choose which statements run. That
means it naturally fits in a definition or assignment:
```epsil
sign(n) = "positive" if n > 0 else "not positive"
sign(-7)
// ➔ "not positive"
```
Choose the compact conditional when both outcomes are simple expressions. Use
the block form when either branch needs local work:
```epsil
function describe(n) {
if n % 2 == 0 { "even" } else { "odd" }
}
describe(42)
// ➔ "even"
```
The same expression-oriented style applies to `match` and blocks. It lets the
shape of a computation stay close to the shape of the value it produces.
## Transform collections in their natural order
Lists are ordered and indexed from 1. Ranges such as `1..10` include both
endpoints. Use a pipeline when data goes through several transformations:
```epsil
1..10
|> Filter(_, n |-> n % 2 == 0)
|> Map(n |-> n^2, _)
|> Sum
// ➔ 220
```
Pipelines read from input to result, rather than inside out. The `_` marks the
argument position filled by the piped value, which matters when `Map` or
`Filter` has another argument as well.
For work whose purpose is changing a binding — an accumulator, for example —
use a loop:
```epsil
let total = 0
for n in 1..100 { total = total + n }
total
// ➔ 5050
```
Use `Map`, `Filter`, and `Reduce` for value-producing iteration; use `for` and
`while` when performing a sequence of updates is the clearest model.
## Types document important boundaries
Epsil infers types for ordinary code, so annotations are optional. Write one
where it communicates an assumption that callers must meet:
```epsil
meanOfPair(a: real, b: real) -> real = (a + b) / 2
meanOfPair(2, 7)
// ➔ 9/2
```
Here the annotation is useful because the function models a numerical
operation, not because every local calculation requires paperwork. It lets
Epsil reject an unsuitable argument at the call boundary instead of leaving a
surprising expression downstream.
## Keep going
The [Getting Started](/getting-started/) guide shows how to run Epsil in
the REPL, from a file, and from JavaScript. Then choose a guide based on the
problem in front of you:
<ReadMore path="/examples/">
Browse **complete programs** for calculus, statistics, linear algebra,
strings, collections, and more.
</ReadMore>
<ReadMore path="/control-flow/">
Learn **functions, pattern matching, loops, blocks, and pipelines** in depth.
</ReadMore>
<ReadMore path="/from-python/">
Translate familiar **Python idioms**, including the differences that matter for
exact arithmetic and 1-based indexing.
</ReadMore>
When you need a precise rule rather than a guided explanation, use the
[Language Reference](/introduction/#language-reference).
---
# Epsil Examples
Source: https://epsil.dev/examples/
# Examples
Complete Epsil programs, from simple iteration to symbolic computation.
Every example on this page is executable as written. The documentation test
executes each code fence directly through `executeEpsil`, while
`test/epsil/programs.test.ts` provides deeper assertions for representative
results and runtime behavior.
A few idioms these programs rely on:
- Loops (`for`, `while`) are evaluated **for effect** — accumulate into a
variable (a number, or a list built up with `Join`/`Append`), or use
`Map`/`Filter`/`Reduce` for value-producing iteration.
- `1..n` is the **inclusive** range from 1 to n, and `x |> f` pipes a value
into a function — when the function takes several arguments, `_` marks the
piped value's slot (`xs |> Map(f, _)`).
- `a if c else b` is the conditional expression — the same `If` as
`if c { a } else { b }`, without the braces.
- Collection **literals** evaluate their elements; lazy **operators**
(`Range`, `Map`, `Filter`) are generators that enumerate on demand (see
[Evaluation](/evaluation/)).
- `a % b` is the remainder (`Mod`), and a postfix `!` is the factorial. The
`!` must directly follow its operand (`n!`; `x != y` is still ≠).
- A tuple pattern binds several names at once — `let (q, r) = …` declares
them, `(a, b) := …` writes ones that already exist. The right side is
evaluated before anything is written, so `(a, b) := (b, a)` swaps. It must
be spelled `:=` (see [declarations](/declarations/)).
## Iteration and Accumulation
**Sum of the multiples of 3 or 5 below 100.** A `for` loop over a range,
accumulating into a variable:
```epsil
let total = 0
for k in 1..99 {
if k % 3 == 0 || k % 5 == 0 { total = total + k }
}
total
// ➔ 2318
```
**FizzBuzz, as a value.** `if`/`else` is an expression, so the whole program
is a single `Map` — no printing, no mutation:
```epsil
Map(k |->
if k % 15 == 0 { "FizzBuzz" }
else if k % 3 == 0 { "Fizz" }
else if k % 5 == 0 { "Buzz" }
else { k },
1..15)
// ➔ [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
```
**Collatz stopping time.** A `while` loop whose body chooses the next value
with a conditional expression:
```epsil
let n = 27
let steps = 0
while n != 1 {
n = n / 2 if n % 2 == 0 else 3n + 1
steps = steps + 1
}
steps
// ➔ 111
```
**Euclid's algorithm.** The classic GCD. The loop step rewrites the pair at
once with a destructuring assignment, so no temporary is needed — the right
side is fully evaluated before either name is written:
```epsil
let a = 1071
let b = 462
while b != 0 {
(a, b) := (b, a % b)
}
a
// ➔ 21
```
**Collecting values in a loop.** A list accumulates through `Join`; each
appended literal snapshots the loop variable's current value:
```epsil
let xs = []
for k in 1..3 { xs = Join(xs, [k]) }
xs
// ➔ [1, 2, 3]
```
**Iterative Fibonacci.** The same pair-carrying step — `(a, b) := (b, a + b)`
is the whole loop body:
```epsil
let a = 0
let b = 1
for k in 1..20 {
(a, b) := (b, a + b)
}
a
// ➔ 6765
```
**A trial-division primality test.** A function with a typed parameter and a
block body, used to count the primes below 100:
```epsil
isPrime(n: integer) = if n < 2 { False } else {
let d = 2
let prime = True
while d * d <= n {
if n % d == 0 { prime = False; d = n } else { d = d + 1 }
}
prime
}
let count = 0
for k in 2..99 { if isPrime(k) { count = count + 1 } }
count
// ➔ 25
```
## Control Flow and Predicates
**Nested loops.** Each `while` owns its own block-scoped counter; the inner
loop re-runs in full for every pass of the outer one. Here Σ i·j over
1 ≤ i, j ≤ 3 is (1+2+3)² = 36:
```epsil
let i = 1
let total = 0
while i <= 3 {
let j = 1
while j <= 3 { total = total + i * j; j = j + 1 }
i = i + 1
}
total
// ➔ 36
```
**Chained comparisons.** A chain like `1 < x <= 4` reads as the conjunction
`1 < x && x <= 4`:
```epsil
let x = 4
let y = 5
(1 < x <= 4, 1 < y <= 4)
// ➔ (True, False)
```
**A truth table**, as a `Map` over the four boolean pairs:
```epsil
Map(p |-> p[1] && p[2],
[(True, True), (True, False), (False, True), (False, False)])
// ➔ [True, False, False, False]
```
## Integers and Number Theory
**Modular exponentiation.** `a^b % m` is computed exactly, then reduced. By
Fermat's little theorem 7¹² ≡ 1 (mod 13), and 222 = 18·12 + 6, so:
```epsil
(7^222) % 13
// ➔ 12
```
**gcd/lcm, factorization and divisors** of a number:
```epsil
(GCD(48, 36), LCM(48, 36), FactorInteger(360), Divisors(28))
// ➔ (12, 144, [(2, 3), (3, 2), (5, 1)], [1, 2, 4, 7, 14, 28])
```
**Returning several values.** A function returns a tuple, and a destructuring
declaration unpacks it into names in one statement:
```epsil
divmod(a: integer, b: integer) = (Floor(a / b), a % b)
let (q, r) = divmod(2026, 7)
(q, r)
// ➔ (289, 3)
```
**Arbitrary-precision integers.** The iterative Fibonacci, with the running
pair carried in a two-element list literal, stays exact all the way to F(200)
— far past the 2⁵³ limit of floating point:
```epsil
Fold((p, _) |-> [p[2], p[1] + p[2]], [0, 1], 1..200)[1]
// ➔ 280571172992510140037611932413038677189525
```
## Recursion
A recursive function refers to itself by name — a one-step definition just
works, because the name is declared before the body is processed. Definition
statements **accumulate**: repeating a name with a different parameter list
adds a *clause*, and a call dispatches to the most specific clause that
matches — so a base case is a literal-parameter clause rather than an `if`
(see [Multiple clauses](/control-flow/#multiple-clauses-literal-parameters)):
```epsil
fact(0) = 1
fact(n: integer) = n * fact(n - 1)
fact(10)
// ➔ 3628800
```
**Multi-clause Fibonacci**, with two base clauses:
```epsil
fib(0) = 0
fib(1) = 1
fib(n: integer) = fib(n - 1) + fib(n - 2)
Map(fib, 1..10)
// ➔ [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```
A single-clause spelling with a conditional is equivalent
(`fact(n) = 1 if n <= 1 else n * fact(n - 1)`), as is the two-step form —
declare with `let`, then assign a `|->` lambda. Note that *mutually*
recursive functions still require declaring all the names with `let` before
defining any of them.
## Higher-Order Functions
Functions are values: they can be passed as arguments and returned from other
functions. A `|->` lambda captures the variables in scope where it is created.
**A numeric-derivative factory.** `deriv` returns a lambda that closes over
both the function `f` and the step `h`. The central-difference estimate is
computed *exactly* (as a rational):
```epsil
deriv(f, h) = x |-> (f(x + h) - f(x - h)) / (2h)
g(x) = x^3
let dg = deriv(g, 1/1000)
dg(2)
// ➔ 12000001/1000000
```
Pipe the call into `N` for a floating-point value — numericization reaches
through the user-function/closure call:
```epsil
deriv(f, h) = x |-> (f(x + h) - f(x - h)) / (2h)
g(x) = x^3
let dg = deriv(g, 1/1000)
dg(2) |> N
// ➔ 12.000001
```
**Function composition.** `compose` returns `f ∘ g`; the two orders give
different results, confirming each lambda captures the right binding:
```epsil
compose(f, g) = x |-> f(g(x))
inc(x) = x + 1
sq(x) = x^2
let h = compose(sq, inc)
(h(4), compose(inc, sq)(4))
// ➔ (25, 17)
```
**A counter factory.** `makeCounter` returns a zero-parameter lambda
(`() |-> …`) whose **block body** (`do { … }`) runs several statements and
yields the last one. The lambda closes over `count` and mutates it on each
call:
```epsil
function makeCounter() {
let count = 0
() |-> do { count = count + 1; count }
}
let c = makeCounter()
c()
c()
c()
// ➔ 3
```
`do { … }` opens a statement block in expression position: it evaluates its
statements in order and its value is the final one (a bare `{ … }` there is a
set/dictionary literal instead). `() |-> …` is a lambda that takes no
parameters.
Each `makeCounter()` call captures its own `count`, so counters are
independent:
```epsil
function makeCounter() {
let count = 0
() |-> do { count = count + 1; count }
}
let a = makeCounter()
let b = makeCounter()
[a(), a(), b(), a()]
// ➔ [1, 2, 1, 3]
```
## Numeric Methods
**Newton's method for √2.** The iteration runs exactly (each `x` is a
rational number); `N(…)` converts the final result to a float:
```epsil
let x = 1
for k in 1..6 { x = (x + 2/x) / 2 }
N(x)
// ➔ 1.4142135623730950488
```
**Trapezoidal integration** of x² over [0, 1]:
```epsil
g(x) = x^2
let n = 100
let h = 1/n
let area = (g(0) + g(1)) / 2
for k in 1..n - 1 { area = area + g(k * h) }
N(area * h)
// ➔ 0.33335
```
**Monte Carlo estimate of π.** `Random()` returns a uniform value in [0, 1):
```epsil
let inside = 0
let total = 500
for k in 1..total {
let px = Random()
let py = Random()
if px^2 + py^2 < 1 { inside = inside + 1 }
}
N(4 * inside / total)
// ➔ ≈ 3.14 (varies by run)
```
**Reproducible simulations.** `WithRandomSeed(seed, body)` evaluates `body`
with a seeded random frame. The block replays exactly, while repeated draws
*inside* it still differ (the n-th draw of a frame is `hash(seed, n)`). Frames
nest, and the innermost one wins. Outside any frame, draws are live:
```epsil
let a = WithRandomSeed(7, [Random(1..100), Random(1..100)])
let b = WithRandomSeed(7, [Random(1..100), Random(1..100)])
a == b
// ➔ True
```
## Calculus
The calculus operators work symbolically, keeping parameters exact.
**Integration.** The work to stretch an ideal spring (force `F = kx`) from 0 to
a displacement `d` is `∫₀ᵈ kx dx`:
```epsil
Integrate(k*x, (x, 0, d))
// ➔ 1/2 * k * d^2
```
A definite integral with numeric bounds evaluates exactly:
```epsil
Integrate(Sin(x), (x, 0, Pi))
// ➔ 2
```
**Limits.** The leading relative error of the small-angle approximation
`sin x ≈ x` is governed by a limit at 0:
```epsil
Limit((Sin(x) - x)/x^3, x, 0)
// ➔ -1/6
```
**Series.** The Maclaurin expansion of sine, with a `BigO` tail marking the
first dropped term:
```epsil
Series(Sin(x), x, 0)
// ➔ x - 1/6 * x^3 + 1/120 * x^5 + BigO(x^7)
```
## Units and Measurements
Units and measured quantities enter through `$…$` LaTeX islands and carry
through the computation.
**Unit conversion.** Convert a posted 30 km/h speed limit to SI m/s:
```epsil
N(UnitConvert($30\,\mathrm{km/h}$, $\mathrm{m/s}$))
// ➔ 8.333333333333334 m/s
```
**Uncertainty propagation.** `Measurement(value, error)` carries an absolute
uncertainty that `*` propagates in quadrature. For a plot measured
L = 10 ± 0.1 m by W = 20 ± 0.2 m, the area error is
√(20²·0.1² + 10²·0.2²) = √8 ≈ 2.83:
```epsil
let L = Measurement(10, 0.1)
let W = Measurement(20, 0.2)
N(L * W)
// ➔ 200.0 ± 2.8
```
## Complex Numbers
The imaginary unit is `i`; complex arithmetic, `Conjugate` and `Abs` (the
modulus) all work:
```epsil
((2 + 3i) * (1 - i), Conjugate(2 + 3i), Abs(3 + 4i))
// ➔ ((5 + i), (2 - 3i), 5)
```
**Euler's formula stays exact.** `e^{iπ/3}` is assembled from the exact
cos(π/3) = 1/2 and sin(π/3) = √3/2, without ever numericizing:
```epsil
$e^{i\pi/3}$
// ➔ 1/2 + sqrt(3)/2i
```
**A product of complex numbers** taken over a mapped `Range` keeps its
imaginary part: (1+i)(2+i)(3+i) = 10i:
```epsil
Product(Map(k |-> k + i, Range(1, 3)))
// ➔ 10i
```
## Exact and Symbolic Computation
These examples show what sets Epsil apart from a conventional language: the
values flowing through a program are mathematical expressions, so arithmetic
is exact and results can be symbolic.
**Exact rationals.** The 20th harmonic number, accumulated in a loop, stays
an exact rational — no floating-point drift:
```epsil
let h = 0
for k in 1..20 { h = h + 1/k }
h
// ➔ 55835135/15519504
```
**The Basel problem.** An exact partial sum compared against the limit
π²/6 — the difference is the tail of the series, ≈ 1/100: