-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
basedocs.jl
3883 lines (2972 loc) · 95.7 KB
/
basedocs.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
#
module BaseDocs
@nospecialize # don't specialize on any arguments of the methods declared herein
struct Keyword
name::Symbol
end
macro kw_str(text)
return Keyword(Symbol(text))
end
"""
**Welcome to Julia $(string(VERSION)).** The full manual is available at
https://docs.julialang.org
as well as many great tutorials and learning resources:
https://julialang.org/learning/
For help on a specific function or macro, type `?` followed
by its name, e.g. `?cos`, or `?@time`, and press enter.
Type `;` to enter shell mode, `]` to enter package mode.
To exit the interactive session, type `CTRL-D` (press the
control key together with the `d` key), or type `exit()`.
"""
kw"help", kw"Julia", kw"julia", kw""
"""
using
`using Foo` will load the module or package `Foo` and make its [`export`](@ref)ed names
available for direct use. Names can also be used via dot syntax (e.g. `Foo.foo` to access
the name `foo`), whether they are `export`ed or not.
See the [manual section about modules](@ref modules) for details.
!!! note
When two or more packages/modules export a name and that name does not refer to the
same thing in each of the packages, and the packages are loaded via `using` without
an explicit list of names, it is an error to reference that name without qualification.
It is thus recommended that code intended to be forward-compatible with future versions
of its dependencies and of Julia, e.g., code in released packages, list the names it
uses from each loaded package, e.g., `using Foo: Foo, f` rather than `using Foo`.
"""
kw"using"
"""
import
`import Foo` will load the module or package `Foo`.
Names from the imported `Foo` module can be accessed with dot syntax
(e.g. `Foo.foo` to access the name `foo`).
See the [manual section about modules](@ref modules) for details.
"""
kw"import"
"""
export
`export` is used within modules to tell Julia which names should be
made available to the user. For example: `export foo` makes the name
`foo` available when [`using`](@ref) the module.
See the [manual section about modules](@ref modules) for details.
"""
kw"export"
"""
public
`public` is used within modules to tell Julia which names are part of the
public API of the module. For example: `public foo` indicates that the name
`foo` is public, without making it available when [`using`](@ref) the module.
As [`export`](@ref) already indicates that a name is public, it is
unnecessary and an error to declare a name both as `public` and as `export`ed.
See the [manual section about modules](@ref modules) for details.
!!! compat "Julia 1.11"
The public keyword was added in Julia 1.11. Prior to this the notion
of publicness was less explicit.
"""
kw"public"
"""
as
`as` is used as a keyword to rename an identifier brought into scope by
`import` or `using`, for the purpose of working around name conflicts as
well as for shortening names. (Outside of `import` or `using` statements,
`as` is not a keyword and can be used as an ordinary identifier.)
`import LinearAlgebra as LA` brings the imported `LinearAlgebra` standard library
into scope as `LA`.
`import LinearAlgebra: eigen as eig, cholesky as chol` brings the `eigen` and `cholesky` methods
from `LinearAlgebra` into scope as `eig` and `chol` respectively.
`as` works with `using` only when individual identifiers are brought into scope.
For example, `using LinearAlgebra: eigen as eig` or `using LinearAlgebra: eigen as eig, cholesky as chol` works,
but `using LinearAlgebra as LA` is invalid syntax, since it is nonsensical to
rename *all* exported names from `LinearAlgebra` to `LA`.
"""
kw"as"
"""
abstract type
`abstract type` declares a type that cannot be instantiated, and serves only as a node in the
type graph, thereby describing sets of related concrete types: those concrete types
which are their descendants. Abstract types form the conceptual hierarchy which makes
Julia’s type system more than just a collection of object implementations. For example:
```julia
abstract type Number end
abstract type Real <: Number end
```
[`Number`](@ref) has no supertype, whereas [`Real`](@ref) is an abstract subtype of `Number`.
"""
kw"abstract type", kw"abstract"
"""
module
`module` declares a [`Module`](@ref), which is a separate global variable workspace. Within a
module, you can control which names from other modules are visible (via importing), and
specify which of your names are intended to be public (via `export` and `public`).
Modules allow you to create top-level definitions without worrying about name conflicts
when your code is used together with somebody else’s.
See the [manual section about modules](@ref modules) for more details.
# Examples
```julia
module Foo
import Base.show
export MyType, foo
struct MyType
x
end
bar(x) = 2x
foo(a::MyType) = bar(a.x) + 1
show(io::IO, a::MyType) = print(io, "MyType \$(a.x)")
end
```
"""
kw"module"
"""
__init__
The `__init__()` function in a module executes immediately *after* the module is loaded at
runtime for the first time. It is called once, after all other statements in the module
have been executed. Because it is called after fully importing the module, `__init__`
functions of submodules will be executed first. Two typical uses of `__init__` are calling
runtime initialization functions of external C libraries and initializing global constants
that involve pointers returned by external libraries.
See the [manual section about modules](@ref modules) for more details.
See also: [`OncePerProcess`](@ref).
# Examples
```julia
const foo_data_ptr = Ref{Ptr{Cvoid}}(0)
function __init__()
ccall((:foo_init, :libfoo), Cvoid, ())
foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Cvoid}, ())
nothing
end
```
"""
kw"__init__"
"""
baremodule
`baremodule` declares a module that does not contain `using Base` or local definitions of
[`eval`](@ref Main.eval) and [`include`](@ref Base.include). It does still import `Core`. In other words,
```julia
module Mod
...
end
```
is equivalent to
```julia
baremodule Mod
using Base
eval(x) = Core.eval(Mod, x)
include(p) = Base.include(Mod, p)
...
end
```
"""
kw"baremodule"
"""
primitive type
`primitive type` declares a concrete type whose data consists only of a series of bits. Classic
examples of primitive types are integers and floating-point values. Some example built-in
primitive type declarations:
```julia
primitive type Char 32 end
primitive type Bool <: Integer 8 end
```
The number after the name indicates how many bits of storage the type requires. Currently,
only sizes that are multiples of 8 bits are supported.
The [`Bool`](@ref) declaration shows how a primitive type can be optionally
declared to be a subtype of some supertype.
"""
kw"primitive type"
"""
macro
`macro` defines a method for inserting generated code into a program.
A macro maps a sequence of argument expressions to a returned expression, and the
resulting expression is substituted directly into the program at the point where
the macro is invoked.
Macros are a way to run generated code without calling [`eval`](@ref Main.eval),
since the generated code instead simply becomes part of the surrounding program.
Macro arguments may include expressions, literal values, and symbols. Macros can be defined for
variable number of arguments (varargs), but do not accept keyword arguments.
Every macro also implicitly gets passed the arguments `__source__`, which contains the line number
and file name the macro is called from, and `__module__`, which is the module the macro is expanded
in.
See the manual section on [Metaprogramming](@ref) for more information about how to write a macro.
# Examples
```jldoctest
julia> macro sayhello(name)
return :( println("Hello, ", \$name, "!") )
end
@sayhello (macro with 1 method)
julia> @sayhello "Charlie"
Hello, Charlie!
julia> macro saylots(x...)
return :( println("Say: ", \$(x...)) )
end
@saylots (macro with 1 method)
julia> @saylots "hey " "there " "friend"
Say: hey there friend
```
"""
kw"macro"
"""
__module__
The argument `__module__` is only visible inside the macro, and it provides information
(in the form of a `Module` object) about the expansion context of the macro invocation.
See the manual section on [Macro invocation](@ref) for more information.
"""
kw"__module__"
"""
__source__
The argument `__source__` is only visible inside the macro, and it provides information
(in the form of a `LineNumberNode` object) about the parser location of the `@` sign from
the macro invocation. See the manual section on [Macro invocation](@ref) for more information.
"""
kw"__source__"
"""
local
`local` introduces a new local variable.
See the [manual section on variable scoping](@ref scope-of-variables) for more information.
# Examples
```jldoctest
julia> function foo(n)
x = 0
for i = 1:n
local x # introduce a loop-local x
x = i
end
x
end
foo (generic function with 1 method)
julia> foo(10)
0
```
"""
kw"local"
"""
global
`global x` makes `x` in the current scope and its inner scopes refer to the global
variable of that name.
See the [manual section on variable scoping](@ref scope-of-variables) for more information.
# Examples
```jldoctest
julia> z = 3
3
julia> function foo()
global z = 6 # use the z variable defined outside foo
end
foo (generic function with 1 method)
julia> foo()
6
julia> z
6
```
"""
kw"global"
"""
for outer
Reuse an existing local variable for iteration in a `for` loop.
See the [manual section on variable scoping](@ref scope-of-variables) for more information.
See also [`for`](@ref).
# Examples
```jldoctest
julia> function f()
i = 0
for i = 1:3
# empty
end
return i
end;
julia> f()
0
```
```jldoctest
julia> function f()
i = 0
for outer i = 1:3
# empty
end
return i
end;
julia> f()
3
```
```jldoctest
julia> i = 0 # global variable
for outer i = 1:3
end
ERROR: syntax: no outer local variable declaration exists for "for outer"
[...]
```
"""
kw"outer"
"""
' '
A pair of single-quote characters delimit a [`Char`](@ref) (that is, character) literal.
# Examples
```jldoctest
julia> 'j'
'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)
```
"""
kw"''"
"""
=
`=` is the assignment operator.
* For variable `a` and expression `b`, `a = b` makes `a` refer to the value of `b`.
* For functions `f(x)`, `f(x) = x` defines a new function constant `f`, or adds a new method to `f` if `f` is already defined; this usage is equivalent to `function f(x); x; end`.
* `a[i] = v` calls [`setindex!`](@ref)`(a,v,i)`.
* `a.b = c` calls [`setproperty!`](@ref)`(a,:b,c)`.
* Inside a function call, `f(a=b)` passes `b` as the value of keyword argument `a`.
* Inside parentheses with commas, `(a=1,)` constructs a [`NamedTuple`](@ref).
# Examples
Assigning `a` to `b` does not create a copy of `b`; instead use [`copy`](@ref) or [`deepcopy`](@ref).
```jldoctest
julia> b = [1]; a = b; b[1] = 2; a
1-element Array{Int64, 1}:
2
julia> b = [1]; a = copy(b); b[1] = 2; a
1-element Array{Int64, 1}:
1
```
Collections passed to functions are also not copied. Functions can modify (mutate) the contents of the objects their arguments refer to. (The names of functions which do this are conventionally suffixed with '!'.)
```jldoctest
julia> function f!(x); x[:] .+= 1; end
f! (generic function with 1 method)
julia> a = [1]; f!(a); a
1-element Array{Int64, 1}:
2
```
Assignment can operate on multiple variables in parallel, taking values from an iterable:
```jldoctest
julia> a, b = 4, 5
(4, 5)
julia> a, b = 1:3
1:3
julia> a, b
(1, 2)
```
Assignment can operate on multiple variables in series, and will return the value of the right-hand-most expression:
```jldoctest
julia> a = [1]; b = [2]; c = [3]; a = b = c
1-element Array{Int64, 1}:
3
julia> b[1] = 2; a, b, c
([2], [2], [2])
```
Assignment at out-of-bounds indices does not grow a collection. If the collection is a [`Vector`](@ref) it can instead be grown with [`push!`](@ref) or [`append!`](@ref).
```jldoctest
julia> a = [1, 1]; a[3] = 2
ERROR: BoundsError: attempt to access 2-element Array{Int64, 1} at index [3]
[...]
julia> push!(a, 2, 3)
4-element Array{Int64, 1}:
1
1
2
3
```
Assigning `[]` does not eliminate elements from a collection; instead use [`filter!`](@ref).
```jldoctest
julia> a = collect(1:3); a[a .<= 1] = []
ERROR: DimensionMismatch: tried to assign 0 elements to 1 destinations
[...]
julia> filter!(x -> x > 1, a) # in-place & thus more efficient than a = a[a .> 1]
2-element Array{Int64, 1}:
2
3
```
"""
kw"="
"""
.=
Perform broadcasted assignment. The right-side argument is expanded as in
[`broadcast`](@ref) and then assigned into the left-side argument in-place.
Fuses with other dotted operators in the same expression; i.e. the whole
assignment expression is converted into a single loop.
`A .= B` is similar to `broadcast!(identity, A, B)`.
# Examples
```jldoctest
julia> A = zeros(4, 4); B = [1, 2, 3, 4];
julia> A .= B
4×4 Array{Float64, 2}:
1.0 1.0 1.0 1.0
2.0 2.0 2.0 2.0
3.0 3.0 3.0 3.0
4.0 4.0 4.0 4.0
julia> A
4×4 Array{Float64, 2}:
1.0 1.0 1.0 1.0
2.0 2.0 2.0 2.0
3.0 3.0 3.0 3.0
4.0 4.0 4.0 4.0
```
"""
kw".="
"""
.
The dot operator is used to access fields or properties of objects and access
variables defined inside modules.
In general, `a.b` calls `getproperty(a, :b)` (see [`getproperty`](@ref Base.getproperty)).
# Examples
```jldoctest
julia> z = 1 + 2im; z.im
2
julia> Iterators.product
product (generic function with 1 method)
```
"""
kw"."
"""
let
`let` blocks create a new hard scope and optionally introduce new local bindings.
Just like the [other scope constructs](@ref man-scope-table), `let` blocks define
the block of code where newly introduced local variables are accessible.
Additionally, the syntax has a special meaning for comma-separated assignments
and variable names that may optionally appear on the same line as the `let`:
```julia
let var1 = value1, var2, var3 = value3
code
end
```
The variables introduced on this line are local to the `let` block and the assignments are
evaluated in order, with each right-hand side evaluated in the scope
without considering the name on the left-hand side. Therefore it makes
sense to write something like `let x = x`, since the two `x` variables are distinct with
the left-hand side locally shadowing the `x` from the outer scope. This can even
be a useful idiom as new local variables are freshly created each time local scopes
are entered, but this is only observable in the case of variables that outlive their
scope via closures. A `let` variable without an assignment, such as `var2` in the
example above, declares a new local variable that is not yet bound to a value.
By contrast, [`begin`](@ref) blocks also group multiple expressions together but do
not introduce scope or have the special assignment syntax.
### Examples
In the function below, there is a single `x` that is iteratively updated three times by the `map`.
The closures returned all reference that one `x` at its final value:
```jldoctest
julia> function test_outer_x()
x = 0
map(1:3) do _
x += 1
return ()->x
end
end
test_outer_x (generic function with 1 method)
julia> [f() for f in test_outer_x()]
3-element Vector{Int64}:
3
3
3
```
If, however, we add a `let` block that introduces a _new_ local variable we will end up
with three distinct variables being captured (one at each iteration) even though we
chose to use (shadow) the same name.
```jldoctest
julia> function test_let_x()
x = 0
map(1:3) do _
x += 1
let x = x
return ()->x
end
end
end
test_let_x (generic function with 1 method)
julia> [f() for f in test_let_x()]
3-element Vector{Int64}:
1
2
3
```
All scope constructs that introduce new local variables behave this way
when repeatedly run; the distinctive feature of `let` is its ability
to succinctly declare new `local`s that may shadow outer variables of the same
name. For example, directly using the argument of the `do` function similarly
captures three distinct variables:
```jldoctest
julia> function test_do_x()
map(1:3) do x
return ()->x
end
end
test_do_x (generic function with 1 method)
julia> [f() for f in test_do_x()]
3-element Vector{Int64}:
1
2
3
```
"""
kw"let"
"""
quote
`quote` creates multiple expression objects in a block without using the explicit
[`Expr`](@ref) constructor. For example:
```julia
ex = quote
x = 1
y = 2
x + y
end
```
Unlike the other means of quoting, `:( ... )`, this form introduces `QuoteNode` elements
to the expression tree, which must be considered when directly manipulating the tree.
For other purposes, `:( ... )` and `quote .. end` blocks are treated identically.
"""
kw"quote"
"""
@
The at sign followed by a macro name marks a macro call. Macros provide the
ability to include generated code in the final body of a program. A macro maps
a tuple of arguments, expressed as space-separated expressions or a
function-call-like argument list, to a returned *expression*. The resulting
expression is compiled directly into the surrounding code. See
[Metaprogramming](@ref man-macros) for more details and examples.
"""
kw"@"
"""
{}
Curly braces are used to specify [type parameters](@ref man-parametric-types).
Type parameters allow a single type declaration to introduce a whole family of
new types — one for each possible combination of parameter values. For example,
the [`Set`](@ref) type describes many possible types of sets; it uses one type
parameter to describe the type of the elements it contains. The specific _parameterized_
types `Set{Float64}` and `Set{Int64}` describe two _concrete_ types: both are
subtypes ([`<:`](@ref)) of `Set`, but the former has `Float64` elements and the latter
has `Int64` elements.
"""
kw"{", kw"{}", kw"}"
"""
[]
Square brackets are used for [indexing](@ref man-array-indexing) ([`getindex`](@ref)),
[indexed assignment](@ref man-indexed-assignment) ([`setindex!`](@ref)),
[array literals](@ref man-array-literals) ([`Base.vect`](@ref)),
[array concatenation](@ref man-array-concatenation) ([`vcat`](@ref), [`hcat`](@ref), [`hvcat`](@ref), [`hvncat`](@ref)),
and [array comprehensions](@ref man-comprehensions) ([`collect`](@ref)).
"""
kw"[", kw"[]", kw"]"
"""
()
Parentheses are used to group expressions, call functions, and construct [tuples](@ref Tuple) and [named tuples](@ref NamedTuple).
"""
kw"(", kw"()", kw")"
"""
#
The number sign (or hash) character is used to begin a single-line comment.
"""
kw"#"
"""
#= =#
A multi-line comment begins with `#=` and ends with `=#`, and may be nested.
"""
kw"#=", kw"=#"
"""
;
Semicolons are used as statement separators and mark the beginning of keyword arguments in function declarations or calls.
"""
kw";"
"""
Expr(head::Symbol, args...)
A type representing compound expressions in parsed julia code (ASTs).
Each expression consists of a `head` `Symbol` identifying which kind of
expression it is (e.g. a call, for loop, conditional statement, etc.),
and subexpressions (e.g. the arguments of a call).
The subexpressions are stored in a `Vector{Any}` field called `args`.
See the manual chapter on [Metaprogramming](@ref) and the developer
documentation [Julia ASTs](@ref).
# Examples
```jldoctest
julia> Expr(:call, :+, 1, 2)
:(1 + 2)
julia> dump(:(a ? b : c))
Expr
head: Symbol if
args: Array{Any}((3,))
1: Symbol a
2: Symbol b
3: Symbol c
```
"""
Expr
"""
:expr
Quote an expression `expr`, returning the abstract syntax tree (AST) of `expr`.
The AST may be of type `Expr`, `Symbol`, or a literal value.
The syntax `:identifier` evaluates to a `Symbol`.
See also: [`Expr`](@ref), [`Symbol`](@ref), [`Meta.parse`](@ref)
# Examples
```jldoctest
julia> expr = :(a = b + 2*x)
:(a = b + 2x)
julia> sym = :some_identifier
:some_identifier
julia> value = :0xff
0xff
julia> typeof((expr, sym, value))
Tuple{Expr, Symbol, UInt8}
```
"""
(:)
"""
\$
Interpolation operator for interpolating into e.g. [strings](@ref string-interpolation)
and [expressions](@ref man-expression-interpolation).
# Examples
```jldoctest
julia> name = "Joe"
"Joe"
julia> "My name is \$name."
"My name is Joe."
```
"""
kw"$"
"""
const
`const` is used to declare global variables whose values will not change. In almost all code
(and particularly performance sensitive code) global variables should be declared
constant in this way.
```julia
const x = 5
```
Multiple variables can be declared within a single `const`:
```julia
const y, z = 7, 11
```
Note that `const` only applies to one `=` operation, therefore `const x = y = 1`
declares `x` to be constant but not `y`. On the other hand, `const x = const y = 1`
declares both `x` and `y` constant.
Note that "constant-ness" does not extend into mutable containers; only the
association between a variable and its value is constant.
If `x` is an array or dictionary (for example) you can still modify, add, or remove elements.
In some cases changing the value of a `const` variable gives a warning instead of
an error.
However, this can produce unpredictable behavior or corrupt the state of your program,
and so should be avoided.
This feature is intended only for convenience during interactive use.
"""
kw"const"
"""
function
Functions are defined with the `function` keyword:
```julia
function add(a, b)
return a + b
end
```
Or the short form notation:
```julia
add(a, b) = a + b
```
The use of the [`return`](@ref) keyword is exactly the same as in other languages,
but is often optional. A function without an explicit `return` statement will return
the last expression in the function body.
"""
kw"function"
"""
x -> y
Create an anonymous function mapping argument(s) `x` to the function body `y`.
```jldoctest
julia> f = x -> x^2 + 2x - 1
#1 (generic function with 1 method)
julia> f(2)
7
```
Anonymous functions can also be defined for multiple arguments.
```jldoctest
julia> g = (x,y) -> x^2 + y^2
#2 (generic function with 1 method)
julia> g(2,3)
13
```
See the manual section on [anonymous functions](@ref man-anonymous-functions) for more details.
"""
kw"->"
"""
return
`return x` causes the enclosing function to exit early, passing the given value `x`
back to its caller. `return` by itself with no value is equivalent to `return nothing`
(see [`nothing`](@ref)).
```julia
function compare(a, b)
a == b && return "equal to"
a < b ? "less than" : "greater than"
end
```
In general you can place a `return` statement anywhere within a function body, including
within deeply nested loops or conditionals, but be careful with `do` blocks. For
example:
```julia
function test1(xs)
for x in xs
iseven(x) && return 2x
end
end
function test2(xs)
map(xs) do x
iseven(x) && return 2x
x
end
end
```
In the first example, the return breaks out of `test1` as soon as it hits
an even number, so `test1([5,6,7])` returns `12`.
You might expect the second example to behave the same way, but in fact the `return`
there only breaks out of the *inner* function (inside the `do` block) and gives a value
back to `map`. `test2([5,6,7])` then returns `[5,12,7]`.
When used in a top-level expression (i.e. outside any function), `return` causes
the entire current top-level expression to terminate early.
"""
kw"return"
"""
if/elseif/else
`if`/`elseif`/`else` performs conditional evaluation, which allows portions of code to
be evaluated or not evaluated depending on the value of a boolean expression. Here is
the anatomy of the `if`/`elseif`/`else` conditional syntax:
```julia
if x < y
println("x is less than y")
elseif x > y
println("x is greater than y")
else
println("x is equal to y")
end
```
If the condition expression `x < y` is true, then the corresponding block is evaluated;
otherwise the condition expression `x > y` is evaluated, and if it is true, the
corresponding block is evaluated; if neither expression is true, the `else` block is
evaluated. The `elseif` and `else` blocks are optional, and as many `elseif` blocks as
desired can be used.
In contrast to some other languages conditions must be of type `Bool`. It does not
suffice for conditions to be convertible to `Bool`.
```jldoctest
julia> if 1 end
ERROR: TypeError: non-boolean (Int64) used in boolean context
```
"""
kw"if", kw"elseif", kw"else"
"""
a ? b : c
Short form for conditionals; read "if `a`, evaluate `b` otherwise evaluate `c`".
Also known as the [ternary operator](https://en.wikipedia.org/wiki/%3F:).
This syntax is equivalent to `if a; b else c end`, but is often used to
emphasize the value `b`-or-`c` which is being used as part of a larger
expression, rather than the side effects that evaluating `b` or `c` may have.
See the manual section on [control flow](@ref man-conditional-evaluation) for more details.
# Examples
```jldoctest
julia> x = 1; y = 2;
julia> x > y ? println("x is larger") : println("x is not larger")
x is not larger
julia> x > y ? "x is larger" : x == y ? "x and y are equal" : "y is larger"
"y is larger"
```
"""
kw"?", kw"?:"
"""
for
`for` loops repeatedly evaluate a block of statements while
iterating over a sequence of values.
The iteration variable is always a new variable, even if a variable of the same name
exists in the enclosing scope.
Use [`outer`](@ref) to reuse an existing local variable for iteration.
# Examples
```jldoctest
julia> for i in [1, 4, 0]
println(i)
end
1
4
0
```
"""
kw"for"
"""
while
`while` loops repeatedly evaluate a conditional expression, and continue evaluating the
body of the while loop as long as the expression remains true. If the condition
expression is false when the while loop is first reached, the body is never evaluated.
# Examples
```jldoctest
julia> i = 1
1
julia> while i < 5
println(i)
global i += 1
end
1