text stringlengths 13 33.9k |
|---|
## [Local Scope](#local-scope)
A new local scope is introduced by most code blocks (see above [table](#man-scope-table) for a complete list). If such a block is syntactically nested inside of another local scope, the scope it creates is nested inside of all the local scopes that it appears within, which are all ultimat... |
## [Local Scope](#local-scope)
Some programming languages require explicitly declaring new variables before using them. Explicit declaration works in Julia too: in any local scope, writing `local x` declares a new local variable in that scope, regardless of whether there is already a variable named `x` in an outer scop... |
## [Local Scope](#local-scope)
1. **Existing local:** If `x` is *already a local variable*, then the existing local `x` is assigned;
2. **Hard scope:** If `x` is *not already a local variable* and assignment occurs inside of any hard scope construct (i.e. within a `let` block, function, struct or macro body, comprehe... |
## [Local Scope](#local-scope)
Now that you know the rules, let's look at some examples. Each example is assumed to be evaluated in a fresh REPL session so that the only globals in each snippet are the ones that are assigned in that block of code.
We'll begin with a nice and clear-cut situation—assignment inside of a h... |
## [Local Scope](#local-scope)
The next clear cut situation we'll consider is when there is already a local variable named `x`, in which case `x = <value>` always assigns to this existing local `x`. This is true whether the assignment occurs in the same local scope, an inner local scope in the same function body, or in... |
## [Local Scope](#local-scope)
Since `s` is local to the function `sum_to`, calling the function has no effect on the global variable `s`. We can also see that the update `s = s + i` in the `for` loop must have updated the same `s` created by the initialization `s = 0` since we get the correct sum of 55 for the integer... |
## [Local Scope](#local-scope)
Note that the local scope of a for loop body is no different from the local scope of an inner function. This means that we could rewrite this example so that the loop body is implemented as a call to an inner helper function and it behaves the same way:
```julia-repl
julia> function sum_t... |
## [Local Scope](#local-scope)
Let's move onto some more ambiguous cases covered by the soft scope rule. We'll explore this by extracting the bodies of the `greet` and `sum_to_def` functions into soft scope contexts. First, let's put the body of `greet` in a `for` loop—which is soft, rather than hard—and evaluate it in... |
## [Local Scope](#local-scope)
The REPL approximates being in the body of a function by deciding whether assignment inside the loop assigns to a global or creates new local based on whether a global variable by that name is defined or not. If a global by the name exists, then the assignment updates it. If no global exi... |
## [Local Scope](#local-scope)
Here we use [`include_string`](../../base/base/#Base.include_string), to evaluate `code` as though it were the contents of a file. We could also save `code` to a file and then call `include` on that file—the result would be the same. As you can see, this behaves quite different from evalu... |
## [Local Scope](#local-scope)
This demonstrates some important aspects of scope: in a scope, each variable can only have one meaning, and that meaning is determined regardless of the order of expressions. The presence of the expression `s = t` in the loop causes `s` to be local to the loop, which means that it is also... |
#### [On Soft Scope](#on-soft-scope)
We have now covered all the local scope rules, but before wrapping up this section, perhaps a few words should be said about why the ambiguous soft scope case is handled differently in interactive and non-interactive contexts. There are two obvious questions one could ask:
1. Why d... |
## [Local Scope](#local-scope)
Obviously the intention is to modify the existing global variable `s`. What else could it mean? However, not all real world code is so short or so clear. We found that code like the following often occurs in the wild:
```julia
x = 123
# much later
# maybe in a different file
for i = 1:1... |
## [Local Scope](#local-scope)
So in Julia 1.0, we simplified the rules for scope: in any local scope, assignment to a name that wasn't already a local variable created a new local variable. This eliminated the notion of soft scope entirely as well as removing the potential for spooky action. We uncovered and fixed a s... |
## [Local Scope](#local-scope)
> Assignment to `s` in soft scope is ambiguous because a global variable by the same name exists: `s` will be treated as a new local. Disambiguate by using `local s` to suppress this warning or `global s` to assign to the existing global variable.
This addresses both issues while preservi... |
### [Let Blocks](#Let-Blocks)
`let` statements create a new *hard scope* block (see above) and introduce new variable bindings each time they run. The variable need not be immediately assigned:
```julia-repl
julia> var1 = let x
for i in 1:5
(i == 4) && (x = i; break)
end
... |
### [Let Blocks](#Let-Blocks)
Here we create and store two closures that return variable `i`. However, it is always the same variable `i`, so the two closures behave identically. We can use `let` to create a new binding for `i`:
```julia-repl
julia> Fs = Vector{Any}(undef, 2); i = 1;
julia> while i <= 2
let... |
### [Loops and Comprehensions](#Loops-and-Comprehensions)
In loops and [comprehensions](../arrays/#man-comprehensions), new variables introduced in their body scopes are freshly allocated for each loop iteration, as if the loop body were surrounded by a `let` block, as demonstrated by this example:
```julia-repl
julia>... |
## [Constants](#Constants)
A common use of variables is giving names to specific, unchanging values. Such variables are only assigned once. This intent can be conveyed to the compiler using the [`const`](../../base/base/#const) keyword:
```julia-repl
julia> const e = 2.71828182845904523536;
julia> const pi = 3.141592... |
## [Constants](#Constants)
- if a new value has the same type as the constant then a warning is printed:
```julia-repl
julia> const y = 1.0
1.0
julia> y = 2.0
WARNING: redefinition of constant y. This may fail, cause incorrect answers, or produce other errors.
2.0
```
- if an assignment would not result in the cha... |
## [Constants](#Constants)
```julia-repl
julia> const x = 1
1
julia> f() = x
f (generic function with 1 method)
julia> f()
1
julia> x = 2
WARNING: redefinition of constant x. This may fail, cause incorrect answers, or produce other errors.
2
julia> f()
1
``` |
## [Typed Globals](#man-typed-globals)
Support for typed globals was added in Julia 1.8
Similar to being declared as constants, global bindings can also be declared to always be of a constant type. This can either be done without assigning an actual value using the syntax `global x::T` or upon assignment as `x::T = 123... |
# Types · The Julia Language
Source: https://docs.julialang.org/en/v1/manual/types/ |
# [Types](#man-types)
Type systems have traditionally fallen into two quite different camps: static type systems, where every program expression must have a type computable before the execution of the program, and dynamic type systems, where nothing is known about types until run time, when the actual values manipulate... |
# [Types](#man-types)
The default behavior in Julia when types are omitted is to allow values to be of any type. Thus, one can write many useful Julia functions without ever explicitly using types. When additional expressiveness is needed, however, it is easy to gradually introduce explicit type annotations into previo... |
# [Types](#man-types)
- There is no division between object and non-object values: all values in Julia are true objects having a type that belongs to a single, fully connected type graph, all nodes of which are equally first-class as types.
- There is no meaningful concept of a "compile-time type": the only type a ... |
## [Type Declarations](#Type-Declarations)
The `::` operator can be used to attach type annotations to expressions and variables in programs. There are two primary reasons to do this:
1. As an assertion to help confirm that your program works the way you expect, and
2. To provide extra type information to the compile... |
## [Type Declarations](#Type-Declarations)
When appended to a variable on the left-hand side of an assignment, or as part of a `local` declaration, the `::` operator means something a bit different: it declares the variable to always have the specified type, like a type declaration in a statically-typed language such a... |
## [Type Declarations](#Type-Declarations)
```julia
function sinc(x)::Float64
if x == 0
return 1
end
return sin(pi*x)/(pi*x)
end
```
Returning from this function behaves just like an assignment to a variable with a declared type: the value is always converted to `Float64`. |
## [Abstract Types](#man-abstract-types)
Abstract types cannot be instantiated, and serve only as nodes in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. We begin with abstract types even though they have no instantiation because they are the backbon... |
## [Abstract Types](#man-abstract-types)
Abstract types are declared using the [`abstract type`](../../base/base/#abstract%20type) keyword. The general syntaxes for declaring an abstract type are:
```julia
abstract type «name» end
abstract type «name» <: «supertype» end
```
The `abstract type` keyword introduces a new ... |
## [Abstract Types](#man-abstract-types)
The [`Number`](../../base/numbers/#Core.Number) type is a direct child type of `Any`, and [`Real`](../../base/numbers/#Core.Real) is its child. In turn, `Real` has two children (it has more, but only two are shown here; we'll get to the others later): [`Integer`](../../base/numb... |
## [Abstract Types](#man-abstract-types)
The first thing to note is that the above argument declarations are equivalent to `x::Any` and `y::Any`. When this function is invoked, say as `myplus(2,5)`, the dispatcher chooses the most specific method named `myplus` that matches the given arguments. (See [Methods](../method... |
## [Primitive Types](#Primitive-Types)
It is almost always preferable to wrap an existing primitive type in a new composite type than to define your own primitive type.
This functionality exists to allow Julia to bootstrap the standard primitive types that LLVM supports. Once they are defined, there is very little reas... |
## [Primitive Types](#Primitive-Types)
The number of bits indicates how much storage the type requires and the name gives the new type a name. A primitive type can optionally be declared to be a subtype of some supertype. If a supertype is omitted, then the type defaults to having `Any` as its immediate supertype. The ... |
## [Primitive Types](#Primitive-Types)
The types [`Bool`](../../base/numbers/#Core.Bool), [`Int8`](../../base/numbers/#Core.Int8) and [`UInt8`](../../base/numbers/#Core.UInt8) all have identical representations: they are eight-bit chunks of memory. Since Julia's type system is nominative, however, they are not intercha... |
## [Composite Types](#Composite-Types)
[Composite types](https://en.wikipedia.org/wiki/Composite_data_type) are called records, structs, or objects in various languages. A composite type is a collection of named fields, an instance of which can be treated as a single value. In many languages, composite types are the on... |
## [Composite Types](#Composite-Types)
Composite types are introduced with the [`struct`](../../base/base/#struct) keyword followed by a block of field names, optionally annotated with types using the `::` operator:
```julia-repl
julia> struct Foo
bar
baz::Int
qux::Float64
end
``... |
## [Composite Types](#Composite-Types)
You can access the field values of a composite object using the traditional `foo.bar` notation:
```julia-repl
julia> foo.bar
"Hello, world."
julia> foo.baz
23
julia> foo.qux
1.5
```
Composite objects declared with `struct` are *immutable*; they cannot be modified after construct... |
## [Composite Types](#Composite-Types)
There is much more to say about how instances of composite types are created, but that discussion depends on both [Parametric Types](#Parametric-Types) and on [Methods](../methods/#Methods), and is sufficiently important to be addressed in its own section: [Constructors](../constr... |
## [Mutable Composite Types](#Mutable-Composite-Types)
If a composite type is declared with `mutable struct` instead of `struct`, then instances of it can be modified:
```julia-repl
julia> mutable struct Bar
baz
qux::Float64
end
julia> bar = Bar("Hello", 1.5);
julia> bar.qux = 2.0
2.0
ju... |
## [Mutable Composite Types](#Mutable-Composite-Types)
- For composite types, this means that the identity of the values of its fields will never change. When the fields are bits types, that means their bits will never change, for fields whose values are mutable types like arrays, that means the fields will alway... |
## [Mutable Composite Types](#Mutable-Composite-Types)
```julia-repl
julia> mutable struct Baz
a::Int
const b::Float64
end
julia> baz = Baz(1, 1.5);
julia> baz.a = 2
2
julia> baz.b = 2.0
ERROR: setfield!: const field .b of type Baz cannot be changed
[...]
``` |
## [Declared Types](#man-declared-types)
The three kinds of types (abstract, primitive, composite) discussed in the previous sections are actually all closely related. They share the same key properties:
- They are explicitly declared.
- They have names.
- They have explicitly declared supertypes.
- They may ha... |
## [Type Unions](#Type-Unions)
A type union is a special abstract type which includes as objects all instances of any of its argument types, constructed using the special [`Union`](../../base/base/#Core.Union) keyword:
```julia-repl
julia> IntOrString = Union{Int,AbstractString}
Union{Int64, AbstractString}
julia> 1 :... |
## [Parametric Types](#Parametric-Types)
An important and powerful feature of Julia's type system is that it is parametric: types can take parameters, so that type declarations actually introduce a whole family of new types – one for each possible combination of parameter values. There are many languages that support s... |
### [Parametric Composite Types](#man-parametric-composite-types)
Type parameters are introduced immediately after the type name, surrounded by curly braces:
```julia-repl
julia> struct Point{T}
x::T
y::T
end
```
This declaration defines a new parametric type, `Point{T}`, holding two "coord... |
### [Parametric Composite Types](#man-parametric-composite-types)
Concrete `Point` types with different values of `T` are never subtypes of each other:
```julia-repl
julia> Point{Float64} <: Point{Int64}
false
julia> Point{Float64} <: Point{Real}
false
```
This last point is *very* important: even though `Float64 <: R... |
### [Parametric Composite Types](#man-parametric-composite-types)
The efficiency gained by being able to store `Point{Float64}` objects with immediate values is magnified enormously in the case of arrays: an `Array{Float64}` can be stored as a contiguous memory block of 64-bit floating-point values, whereas an `Array{R... |
### [Parametric Composite Types](#man-parametric-composite-types)
How does one construct a `Point` object? It is possible to define custom constructors for composite types, which will be discussed in detail in [Constructors](../constructors/#man-constructors), but in the absence of any special constructor declarations,... |
### [Parametric Composite Types](#man-parametric-composite-types)
In many cases, it is redundant to provide the type of `Point` object one wants to construct, since the types of arguments to the constructor call already implicitly provide type information. For that reason, you can also apply `Point` itself as a constru... |
### [Parametric Abstract Types](#Parametric-Abstract-Types)
Parametric abstract type declarations declare a collection of abstract types, in much the same way:
```julia-repl
julia> abstract type Pointy{T} end
```
With this declaration, `Pointy{T}` is a distinct abstract type for each type or integer value of `T`. As wi... |
### [Parametric Abstract Types](#Parametric-Abstract-Types)
```julia-repl
julia> Point{Float64} <: Pointy{Float64}
true
julia> Point{Real} <: Pointy{Real}
true
julia> Point{AbstractString} <: Pointy{AbstractString}
true
```
This relationship is also invariant:
```julia-repl
julia> Point{Float64} <: Pointy{Real}
false... |
### [Parametric Abstract Types](#Parametric-Abstract-Types)
```julia-repl
julia> Pointy{Float64}
Pointy{Float64}
julia> Pointy{Real}
Pointy{Real}
julia> Pointy{AbstractString}
ERROR: TypeError: in Pointy, in T, expected T<:Real, got Type{AbstractString}
julia> Pointy{1}
ERROR: TypeError: in Pointy, in T, expected T<... |
### [Tuple Types](#Tuple-Types)
Tuples are an abstraction of the arguments of a function – without the function itself. The salient aspects of a function's arguments are their order and their types. Therefore a tuple type is similar to a parameterized immutable type where each parameter is the type of one field. For ex... |
### [Vararg Tuple Types](#Vararg-Tuple-Types)
The last parameter of a tuple type can be the special value [`Vararg`](../../base/base/#Core.Vararg), which denotes any number of trailing elements:
```julia-repl
julia> mytupletype = Tuple{AbstractString,Vararg{Int}}
Tuple{AbstractString, Vararg{Int64}}
julia> isa(("1",),... |
### [Named Tuple Types](#Named-Tuple-Types)
Named tuples are instances of the [`NamedTuple`](../../base/base/#Core.NamedTuple) type, which has two parameters: a tuple of symbols giving the field names, and a tuple type giving the field types. For convenience, `NamedTuple` types are printed using the [`@NamedTuple`](../... |
### [Parametric Primitive Types](#Parametric-Primitive-Types)
Primitive types can also be declared parametrically. For example, pointers are represented as primitive types which would be declared in Julia like this:
```julia
# 32-bit system:
primitive type Ptr{T} 32 end
# 64-bit system:
primitive type Ptr{T} 64 end
``... |
## [UnionAll Types](#UnionAll-Types)
We have said that a parametric type like `Ptr` acts as a supertype of all its instances (`Ptr{Int64}` etc.). How does this work? `Ptr` itself cannot be a normal data type, since without knowing the type of the referenced data the type clearly cannot be used for memory operations. Th... |
## [UnionAll Types](#UnionAll-Types)
The type application syntax `A{B,C}` requires `A` to be a `UnionAll` type, and first substitutes `B` for the outermost type variable in `A`. The result is expected to be another `UnionAll` type, into which `C` is then substituted. So `A{B,C}` is equivalent to `A{B}{C}`. This explain... |
## [UnionAll Types](#UnionAll-Types)
Since `where` expressions nest, type variable bounds can refer to outer type variables. For example `Tuple{T,Array{S}} where S<:AbstractArray{T} where T<:Real` refers to 2-tuples whose first element is some [`Real`](../../base/numbers/#Core.Real), and whose second element is an `Arr... |
## [UnionAll Types](#UnionAll-Types)
This is equivalent to `const Vector = Array{T,1} where T`. Writing `Vector{Float64}` is equivalent to writing `Array{Float64,1}`, and the umbrella type `Vector` has as instances all `Array` objects where the second parameter – the number of array dimensions – is 1, regardless of wha... |
## [Singleton types](#man-singleton-types)
Immutable composite types with no fields are called *singletons*. Formally, if
1. `T` is an immutable composite type (i.e. defined with `struct`),
2. `a isa T && b isa T` implies `a === b`,
then `T` is a singleton type.<sup>[[2\]](#footnote-2)</sup> [`Base.issingletontype`](... |
## [Types of functions](#Types-of-functions)
Each function has its own type, which is a subtype of `Function`.
```julia-repl
julia> foo41(x) = x + 1
foo41 (generic function with 1 method)
julia> typeof(foo41)
typeof(foo41) (singleton type of function foo41, subtype of Function)
```
Note how `typeof(foo41)` prints as i... |
## [Type{T} type selectors](#man-typet-type)
For each type `T`, `Type{T}` is an abstract parametric type whose only instance is the object `T`. Until we discuss [Parametric Methods](../methods/#Parametric-Methods) and [conversions](../conversion-and-promotion/#conversion-and-promotion), it is difficult to explain the u... |
## [Type{T} type selectors](#man-typet-type)
```julia-repl
julia> isa(Type{Float64}, Type)
true
julia> isa(Float64, Type)
true
julia> isa(Real, Type)
true
```
Any object that is not a type is not an instance of `Type`:
```julia-repl
julia> isa(1, Type)
false
julia> isa("foo", Type)
false
```
While `Type` is part of ... |
## [Type Aliases](#Type-Aliases)
Sometimes it is convenient to introduce a new name for an already expressible type. This can be done with a simple assignment statement. For example, `UInt` is aliased to either [`UInt32`](../../base/numbers/#Core.UInt32) or [`UInt64`](../../base/numbers/#Core.UInt64) as is appropriate ... |
## [Operations on Types](#Operations-on-Types)
Since types in Julia are themselves objects, ordinary functions can operate on them. Some functions that are particularly useful for working with or exploring types have already been introduced, such as the `<:` operator, which indicates whether its left hand operand is a ... |
## [Operations on Types](#Operations-on-Types)
If you apply [`supertype`](../../base/base/#Base.supertype) to other type objects (or non-type objects), a [`MethodError`](../../base/base/#Core.MethodError) is raised:
```julia-repl
julia> supertype(Union{Float64,Int64})
ERROR: MethodError: no method matching supertype(::... |
## [Custom pretty-printing](#man-custom-pretty-printing)
Often, one wants to customize how instances of a type are displayed. This is accomplished by overloading the [`show`](../../base/io-network/#Base.show-Tuple%7BIO,%20Any%7D) function. For example, suppose we define a type to represent complex numbers in polar form... |
## [Custom pretty-printing](#man-custom-pretty-printing)
More fine-grained control over display of `Polar` objects is possible. In particular, sometimes one wants both a verbose multi-line printing format, used for displaying a single object in the REPL and other interactive environments, and also a more compact single... |
## [Custom pretty-printing](#man-custom-pretty-printing)
where the single-line `show(io, z)` form is still used for an array of `Polar` values. Technically, the REPL calls `display(z)` to display the result of executing a line, which defaults to `show(stdout, MIME("text/plain"), z)`, which in turn defaults to `show(std... |
## [Custom pretty-printing](#man-custom-pretty-printing)
As a rule of thumb, the single-line `show` method should print a valid Julia expression for creating the shown object. When this `show` method contains infix operators, such as the multiplication operator (`*`) in our single-line `show` method for `Polar` above, ... |
## [Custom pretty-printing](#man-custom-pretty-printing)
The method defined above adds parentheses around the call to `show` when the precedence of the calling operator is higher than or equal to the precedence of multiplication. This check allows expressions which parse correctly without the parentheses (such as `:($a... |
## [Custom pretty-printing](#man-custom-pretty-printing)
```julia-repl
julia> show(IOContext(stdout, :compact=>true), Polar(3, 4.0))
3.0ℯ4.0im
julia> [Polar(3, 4.0) Polar(4.0,5.3)]
1×2 Matrix{Polar{Float64}}:
3.0ℯ4.0im 4.0ℯ5.3im
```
See the [`IOContext`](../../base/io-network/#Base.IOContext) documentation for a lis... |
## ["Value types"](#%22Value-types%22)
In Julia, you can't dispatch on a *value* such as `true` or `false`. However, you can dispatch on parametric types, and Julia allows you to include "plain bits" values (Types, Symbols, Integers, floating-point numbers, tuples, etc.) as type parameters. A common example is the dime... |
## ["Value types"](#%22Value-types%22)
It's worth noting that it's extremely easy to mis-use parametric "value" types, including `Val`; in unfavorable cases, you can easily end up making the performance of your code much *worse*. In particular, you would never want to write actual code as illustrated above. For more in... |
# Methods · The Julia Language
Source: https://docs.julialang.org/en/v1/manual/methods/ |
# [Methods](#Methods)
Recall from [Functions](../functions/#man-functions) that a function is an object that maps a tuple of arguments to a return value, or throws an exception if no appropriate value can be returned. It is common for the same conceptual function or operation to be implemented quite differently for dif... |
# [Methods](#Methods)
To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a functio... |
# [Methods](#Methods)
The choice of which method to execute when a function is applied is called *dispatch*. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments. This is different than traditional o... |
## [Defining Methods](#Defining-Methods)
Until now, we have, in our examples, defined only functions with a single method having unconstrained argument types. Such functions behave just like they would in traditional dynamically typed languages. Nevertheless, we have used multiple dispatch and methods almost continuall... |
## [Defining Methods](#Defining-Methods)
```julia-repl
julia> f(2.0, 3)
ERROR: MethodError: no method matching f(::Float64, ::Int64)
The function `f` exists, but no method is defined for this combination of argument types.
Closest candidates are:
f(::Float64, !Matched::Float64)
@ Main none:1
Stacktrace:
[...]
j... |
## [Defining Methods](#Defining-Methods)
```julia-repl
julia> f(x::Number, y::Number) = 2x - y
f (generic function with 2 methods)
julia> f(2.0, 3)
1.0
```
This method definition applies to any pair of arguments that are instances of [`Number`](../../base/numbers/#Core.Number). They need not be of the same type, so lo... |
## [Defining Methods](#Defining-Methods)
The `2x + y` definition is only used in the first case, while the `2x - y` definition is used in the others. No automatic casting or conversion of function arguments is ever performed: all conversion in Julia is non-magical and completely explicit. [Conversion and Promotion](../... |
## [Defining Methods](#Defining-Methods)
This output tells us that `f` is a function object with two methods. To find out what the signatures of those methods are, use the [`methods`](../../base/base/#Base.methods) function:
```julia-repl
julia> methods(f)
# 2 methods for generic function "f" from Main:
[1] f(x::Float... |
## [Defining Methods](#Defining-Methods)
Note that in the signature of the third method, there is no type specified for the arguments `x` and `y`. This is a shortened way of expressing `f(x::Any, y::Any)`.
Although it seems a simple concept, multiple dispatch on the types of values is perhaps the single most powerful a... |
## [Defining Methods](#Defining-Methods)
Multiple dispatch together with the flexible parametric type system give Julia its ability to abstractly express high-level algorithms decoupled from implementation details. |
## [Method specializations](#man-method-specializations)
When you create multiple methods of the same function, this is sometimes called "specialization." In this case, you're specializing the *function* by adding additional methods to it: each new method is a new specialization of the function. As shown above, these s... |
## [Method specializations](#man-method-specializations)
Julia will compile `mysum` twice, once for `x::Int, y::Int` and again for `x::Float64, y::Float64`. The point of compiling twice is performance: the methods that get called for `+` (which `mysum` uses) vary depending on the specific types of `x` and `y`, and by c... |
## [Method Ambiguities](#man-ambiguities)
It is possible to define a set of function methods such that there is no unique most specific method applicable to some combinations of arguments:
```julia-repl
julia> g(x::Float64, y) = 2x + y
g (generic function with 1 method)
julia> g(x, y::Float64) = x + 2y
g (generic func... |
## [Parametric Methods](#Parametric-Methods)
Method definitions can optionally have type parameters qualifying the signature:
```julia-repl
julia> same_type(x::T, y::T) where {T} = true
same_type (generic function with 1 method)
julia> same_type(x,y) = false
same_type (generic function with 2 methods)
```
The first me... |
## [Parametric Methods](#Parametric-Methods)
The type parameter `T` in this example ensures that the added element `x` is a subtype of the existing eltype of the vector `v`. The `where` keyword introduces a list of those constraints after the method signature definition. This works the same for one-line definitions, as... |
## [Parametric Methods](#Parametric-Methods)
If the type of the appended element does not match the element type of the vector it is appended to, a [`MethodError`](../../base/base/#Core.MethodError) is raised. In the following example, the method's type parameter `T` is used as the return value:
```julia-repl
julia> my... |
## [Parametric Methods](#Parametric-Methods)
```julia-repl
julia> same_type_numeric(x::T, y::T) where {T<:Number} = true
same_type_numeric (generic function with 1 method)
julia> same_type_numeric(x::Number, y::Number) = false
same_type_numeric (generic function with 2 methods)
julia> same_type_numeric(1, 2)
true
ju... |
## [Parametric Methods](#Parametric-Methods)
Parametric methods allow the same syntax as `where` expressions used to write types (see [UnionAll Types](../types/#UnionAll-Types)). If there is only a single parameter, the enclosing curly braces (in `where {T}`) can be omitted, but are often preferred for clarity. Multipl... |
## [Redefining Methods](#Redefining-Methods)
When redefining a method or adding new methods, it is important to realize that these changes don't take effect immediately. This is key to Julia's ability to statically infer and compile code to run fast, without the usual JIT tricks and overhead. Indeed, any new method def... |
## [Redefining Methods](#Redefining-Methods)
However, future calls to `tryeval` will continue to see the definition of `newfun` as it was *at the previous statement at the REPL*, and thus before that call to `tryeval`.
You may want to try this for yourself to see how it works.
The implementation of this behavior is a "... |
## [Redefining Methods](#Redefining-Methods)
```julia-repl
julia> g(x) = f(x)
g (generic function with 1 method)
julia> t = @async f(wait()); yield();
```
Now we add some new methods to `f(x)`:
```julia-repl
julia> f(x::Int) = "definition for Int"
f (generic function with 2 methods)
julia> f(x::Type{Int}) = "definiti... |
## [Design Patterns with Parametric Methods](#Design-Patterns-with-Parametric-Methods)
While complex dispatch logic is not required for performance or usability, sometimes it can be the best way to express some algorithm. Here are a few common design patterns that come up sometimes when using dispatch in this way. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.