Julia é uma linguagem de programação de código aberto, multi-plataforma, de alto nível e alta performance para computação técnica.
Julia has an LLVM Low-Level Virtual Machine (LLVM) is a compiler infrastructure to build intermediate and/or binary machine code. -based JIT Just-In-Time compilation occurs at run-time rather than prior to execution, which means it offers both the speed of compiled code and the flexibility of interpretation. The compiler parses the code and infers types, after which the LLVM code is generated, which in turn is compiled into native code. compiler that allows it to match the performance of languages such as C and FORTRAN without the hassle of low-level code. Because the code is compiled on the fly you can run (bits of) code in a shell or REPL Read-Eval-Print-Loop , which is part of the recommended workflow .
Julia is dynamically typed, provides multiple dispatch Because function argument types are determined at run-time, the compiler can choose the implementation that is optimized for the provided arguments and the processor architecture. , and is designed for parallelism and distributed computation.
Julia has a built-in package manager.
Julia has many built-in mathematical functions, including special functions (e.g. Gamma), and supports complex numbers right out of the box.
Julia allows you to generate code automagically thanks to Lisp-inspired macros.
Julia was born in 2012.
| Atribuição | answer = 42x, y, z = 1, [1:10; ], "A string"x, y = y, x # swap x and y |
| Declaração de constante | const DATE_OF_BIRTH = 2012 |
| Comentário de final de linha | i = 1 # This is a comment |
| Comentário deliminitado | #= This is another comment =# |
| Encadeamento | x = y = z = 1 # right-to-left0 < x < 3 # true5 < x != y < 5 # false |
| Definição de Função | function add_one(i) return i + 1end |
| Inserir simbolos LaTex | \delta + [Tab] |
| Aritmética Básica | +, -,*,/ |
| Exponencial | 2^3 == 8 |
| Divisão | 3/12 == 0.25 |
| Divisao Inversa | 7\3 == 3/7 |
| Resto da Divisão | x % y ou rem(x,y) |
| Negação | !true == false |
| Igualdade | a == b |
| Igualdade ((estrutura) O operador padrão de comparação somente compara endereço de memória para esse tipo de estrutura.) | is(a, b) # feito no nível do bit |
| Desigualdade | a != b ou a ≠ b |
| Menor e Maior | < e > |
| Menor ou igual | <= ou ≤ |
| Maior ou igual | >= ou ≥ |
| Operações elemento a elemento | [1, 2, 3] .+ [1, 2, 3] == [2, 4, 6][1, 2, 3] .* [1, 2, 3] == [1, 4, 9] |
| Não é um número(Not a Number) | isnan(NaN) not(!) NaN == NaN |
| Operador Ternário | a == b ? "Equal" : "Not equal" |
| Operadores de Curto-Circuito(E e OU) | a && b e a || b |
| Equivalência de Objetos | a === b |
| Reutilizar o último resultado | ans |
| Interromper a execução | [Ctrl] + [C] |
| Limpar tela | [Ctrl] + [L] |
| Executar programa | include("filename.jl") |
| Encontrar ajuda relacionada a uma função | ?func |
| Ver todos os locais onde uma função está definida | apropos("func") |
| Modo de linha de comandos | ; |
| Modo de gerenciador de pacotes | ] |
| Modo de ajuda | ? |
| Sair do modo especial / Voltar à REPL | [Backspace] numa linha vazia |
| Sair da REPL | exit() ou [Ctrl] + [D] |
Para ajudar Julia a carregar rapidamente, muitas das funcionalidades principais
existem nas bibliotecas padrão que vem junto com Julia. Para fazer as funções
disponíveis, use using PackageName. Aqui estão algumas Bibliotecas Padrão e
funções comuns.
Random |
rand, randn, randsubseq |
Statistics |
mean, std, cor, median, quantile |
LinearAlgebra |
I, eigvals, eigvecs, det, cholesky |
SparseArrays |
sparse, SparseVector, SparseMatrixCSC |
Distributed |
@distributed, pmap, addprocs |
Dates |
DateTime, Date |
Packages must be registered before they are visible to the
package manager. In Julia 1.0, there are two ways to work with the package manager:
either with using Pkg and using Pkg functions, or by typing ] in the REPL to
enter the special interactive package management mode. (To return to regular REPL, just
hit BACKSPACE on an empty line in package management mode). Note
that new tools arrive in interactive mode first, then usually also
become available in regular Julia sessions through Pkg module.
Pkg in Julia session| List installed packages (human-readable) | Pkg.status() |
| List installed packages (machine-readable) | Pkg.installed() |
| Update all packages | Pkg.update() |
Install PackageName |
Pkg.add("PackageName") |
Rebuild PackageName |
Pkg.build("PackageName") |
Use PackageName (after install) |
using PackageName |
Remove PackageName |
Pkg.rm("PackageName") |
Add PackageName |
add PackageName |
Remove PackageName |
rm PackageName |
Update PackageName |
update PackageName |
| Use development version | dev PackageName or dev GitRepoUrl |
| Stop using development version, revert to public release | free PackageName |
| Character | chr = 'C' |
| String | str = "A string" |
| Character code | Int('J') == 74 |
| Character from code | Char(74) == 'J' |
| Any UTF character | chr = '\uXXXX' # 4-digit HEXchr = '\UXXXXXXXX' # 8-digit HEX |
| Loop through characters | for c in str println(c)end |
| Concatenation | str = "Learn" * " " * "Julia" |
| String interpolation | a = b = 2println("a * b = $(a*b)") |
| First matching character or regular expression | findfirst(isequal('i'), "Julia") == 4 |
| Replace substring or regular expression | replace("Julia", "a" => "us") == "Julius" |
| Last index (of collection) | lastindex("Hello") == 5 |
| Number of characters | length("Hello") == 5 |
| Regular expression | pattern = r"l[aeiou]" |
| Subexpressions | str = "+1 234 567 890"pat = r"\+([0-9]) ([0-9]+)"m = match(pat, str)m.captures == ["1", "234"] |
| All occurrences | [m.match for m = eachmatch(pat, str)] |
| All occurrences (as iterator) | eachmatch(pat, str) |
Beware of multi-byte Unicode encodings in UTF-8:
10 == lastindex("Ångström") != length("Ångström") == 8
Strings are immutable.
| Tipo inteiro | IntN e UIntN, com N ∈ {8, 16, 32, 64, 128}, BigInt |
| Tipos de ponto flutuante | FloatN com N ∈ {16, 32, 64}BigFloat |
| Valores mínimo e máximo por tipo | typemin(Int8)typemax(Int64) |
| Tipo complexo | Complex{T} |
| Unidade imaginária | im |
| Precisão da máquina | eps() # o mesmo que eps(Float64) |
| Arredondamento | round() # ponto flutuanteround(Int, x) # inteiro |
| Conversão de tipo | convert(TypeName, val) # tentativa/errotypename(val) # chama conversor |
| Constantes Globais | pi # 3.1415...π # 3.1415...im # real(im * im) == -1 |
| Outras constantes | using Base.MathConstants |
O Julia não checa automaticamente o overflow numérico. Use o pacote SaferIntegers para inteiros com verificação de overflow.
Muitas funções de números aleatórios requerem using Random.
| Definir semente | seed!(seed) |
| Números aleatórios | rand() # uniforme [0,1)randn() # normal (-Inf, Inf) |
| Aleatório de outras distribuições | using Distributionsminha_dist = Bernoulli(0.2) # Por exemplorand(minha_dist) |
| Subamostra aleatória de elementos de A com probabilidade p de inclusão | randsubseq(A, p) |
| Permutação aleatória de elementos de A | shuffle(A) |
| Declaração | arr = Float64[] |
| Pre-alocação | sizehint!(arr, 10^4) |
| Acesso e atribuição | arr = Any[1,2]arr[1] = "Some text" |
| Comparação | a = [1:10;]b = a # b points to aa[1] = -99a == b # true |
| Copiar elementos (não endereços) | b = copy(a)b = deepcopy(a) |
| Selecionar a subarray de m para n | arr[m:n] |
| n-elemento array com 0.0s | zeros(n) |
| n-elemento array com 1.0s | ones(n) |
| n-elemento array com #undefs | Vector{Type}(undef,n) |
| n números igualmente espaçados do início ao fim | range(start,stop=stop,length=n) |
| Array com n elementos aleatórios Int8 | rand(Int8, n) |
| Preencher array com val | fill!(arr, val) |
| Mostrar ultimo elemento | pop!(arr) |
| Mostrar primeiro elemento | popfirst!(a) |
| Enviar val como último elemento | push!(arr, val) |
| Enviar val como primeiro elemento | pushfirst!(arr, val) |
| Remover elemento em index idx | deleteat!(arr, idx) |
| Ordenar | sort!(arr) |
| Acrescentar a com b | append!(a,b) |
| Verificar se val é um elemento | in(val, arr) or val in arr |
| Produto Escalar | dot(a, b) == sum(a .* b) |
| Alterar dimensões (s possível) | reshape(1:6, 3, 2)' == [1 2 3; 4 5 6] |
| Para String (com delimitador del entre elementos) | join(arr, del) |
Para a maioria das ferramentas de Álgebra Linear, use using LinearAlgebra.
| Matriz Identidade | I # use somente a variável I. Será automaticamente ajustada conforme as dimensões requeridas. |
| Definir Matriz | M = [1 0; 0 1] |
| Dimensão da Matriz | size(M) |
Selecionar i-ésima linha |
M[i, :] |
Slecionar i-ésima coluna |
M[:, i] |
| Concatenar horizontalmente | M = [a b] ou M = hcat(a, b) |
| Concatenar verticalmente | M = [a ; b] ou M = vcat(a, b) |
| Matriz Transposta | transpose(M) |
| Matriz Transposta Conjugada | M' ou adjoint(M) |
| Traço da Matriz | tr(M) |
| Determinante | det(M) |
| Posto da Matriz | rank(M) |
| Autovalores | eigvals(M) |
| Autovetores | eigvecs(M) |
| Matriz Inversa | inv(M) |
Resolver M*x == v |
M\v é melhor Numericamente mais estável e tipicamente mais rápido. que inv(M)*v |
| Pseudo-inversa de Moore-Penrose | pinv(M) |
Julia tem suporte nativo a decomposições matriciais.
Julia tenta inferir se as matrizes são de tipos especiais (Simétricas, Hermitianas, etc.), mas as vezes falha. Para ajudar Julia a despachar algoritmos ótimos, matrizes especiais podem ser declaradas para ter uma estrutura com funções como Symmetric , Hermitian , UpperTriangular, LowerTriangular, Diagonal, e mais.
| Condicional | if-elseif-else-end |
Laço for simples |
for i in 1:10println(i)end |
Mais de um laço for |
for i in 1:10, j = 1:5println(i*j)end |
| Enumeração | for (idx, val) in enumerate(arr)println("o $idx-ésimo elemento é $val")end |
Laço while |
while expressão_booleana# comandosend |
| Sair do laço | break |
| Sair da iteração | continue |
Todos os argumentos das funções são passadas por referências.
Functions with ! appended change at least one argument, typically the first:
sort!(arr).
Required arguments are separated with a comma and use the positional notation.
Optional arguments need a default value in the signature, defined with =.
Keyword arguments use the named notation and are listed in the function’s signature after the semicolon:
function func(req1, req2; key1=dflt1, key2=dflt2)
# do stuff
end
The semicolon is not required in the call to a function that accepts keyword arguments.
The return statement is optional but highly recommended.
Multiple data structures can be returned as a tuple in a single return statement.
Command line arguments julia script.jl arg1 arg2... can be processed from global
constant ARGS:
for arg in ARGS
println(arg)
end
Anonymous functions can best be used in collection functions or list comprehensions:
x -> x^2.
Functions can accept a variable number of arguments:
function func(a...)
println(a)
end
func(1, 2, [3:5]) # tuple: (1, 2, UnitRange{Int64}[3:5])
Functions can be nested:
function outerfunction()
# do some outer stuff
function innerfunction()
# do inner stuff
# can access prior outer definitions
end
# do more outer stuff
end
Functions can have explicit return types
# take any Number subtype and return it as a String
function stringifynumber(num::T)::String where T <: Number
return "$num"
end
Functions can be vectorized by using the Dot Syntax
# here we broadcast the subtraction of each mean value
# by using the dot operator
julia> using Statistics
julia> A = rand(3, 4);
julia> B = A .- mean(A, dims=1)
3×4 Array{Float64,2}:
0.0387438 0.112224 -0.0541478 0.455245
0.000773337 0.250006 0.0140011 -0.289532
-0.0395171 -0.36223 0.0401467 -0.165713
julia> mean(B, dims=1)
1×4 Array{Float64,2}:
-7.40149e-17 7.40149e-17 1.85037e-17 3.70074e-17
Julia generates specialized versions Multiple dispatch a type of polymorphism that dynamically determines which version of a function to call. In this context, dynamic means that it is resolved at run-time, whereas method overloading is resolved at compile time. Julia manages multiple dispatch completely in the background. Of course, you can provide custom function overloadings with type annotations. of functions based on data types. When a function is called with the same argument types again, Julia can look up the native machine code and skip the compilation process.
Since Julia 0.5 the existence of potential ambiguities is still acceptable, but actually calling an ambiguous method is an immediate error.
Stack overflow is possible when recursive functions nest many levels deep. Trampolining can be used to do tail-call optimization, as Julia does not do that automatically yet. Alternatively, you can rewrite the tail recursion as an iteration.
| Dicionário | d = Dict(key1 => val1, key2 => val2, ...)d = Dict(:key1 => val1, :key2 => val2, ...) |
| Todas as chaves (iterador) | keys(d) |
| Todos os valores (iterador) | values(d) |
| Laços pelos pares de chave-valor | for (k,v) in dprintln("chave: $k, valor: $v")end |
Verifica existência de chave :k |
haskey(d, :k) |
| Copiar chaves (ou valores) para um vetor | arr = collect(keys(d))arr = [k for (k,v) in d] |
Dicionários são mutáveis; quando símbolos são usados como chaves, as chaves são imutáveis.
| Declaração | s = Set([1, 2, 3, "Algum texto"]) |
União s1 ∪ s2 |
union(s1, s2) |
Intersecção s1 ∩ s2 |
intersect(s1, s2) |
Diferença s1 \\ s2 |
setdiff(s1, s2) |
Diferença s1 △ s2 |
symdiff(s1, s2) |
Subconjunto s1 ⊆ s2 |
issubset(s1, s2) |
Verificação se um elemento está contido em um conjunto é feita em O(1).
| Apply f to all elements of collection coll | map(f, coll) ormap(coll) do elem# do stuff with elem# must contain returnend |
| Filter coll for true values of f | filter(f, coll) |
| List comprehension | arr = [f(elem) for elem in coll] |
Julia não tem classes e, portanto, não há métodos específicos de classe.
Tipos são como classes sem métodos.
Os tipos abstratos podem ser subtipados, mas não instanciados.
Tipos concretos não podem ser subtipados.
Por padrão, struct s são imutáveis.
Os tipos imutáveis melhoram o desempenho e são seguros para threads, já que podem ser compartilhada entre threads sem a necessidade de sincronização.
Objetos que podem ser de um conjunto de tipos são chamados de tipos Union.
| Anotação de tipo | var::NomeDoTipo |
| Declaração de tipo | struct Programadornome::Stringano_de_nascimento::UInt16linguagem_favorita::AbstractStringend |
| Declaração de tipo mutável | substituir struct por mutable struct |
| Pseudônimo de tipo | const Nerd = Programador |
| Construtores de tipo | methods(NomeDoTipo) |
| Instanciação de tipo | me = Programador("Ian", 1984, "Julia")me = Nerd("Ian", 1984, "Julia") |
| Declaração de subtipo | abstract type Programadornome::AbstractStringano_de_nascimento::UInt16linguagem_favorita::AbstractStringend |
| Tipo paramétrico | struct Ponto{T <: Real}x::Ty::Tendp =Ponto{Float64}(1,2) |
Tipos Union |
Union{Int, String} |
| Hierarquia de tipo transversal | supertype(NomeDoTipo) e subtypes(NomeDoTipo) |
| Supertipo padrão | Any |
| Todos os campos | fieldnames(NomeDoTipo) |
| Todos os tipos de campo | NomeDoTipo.types |
Quando um tipo é definido com um construtor interno, os construtores padrões externos
não estão disponíveis e devem ser definidos manualmente, se necessário.
Um construtor interno é melhor usado para verificar se os parâmetros
estão em conformidade com certas condições (invariância). Obviamente, essas invariantes
podem ser violadas acessando e modificando os campos diretamente, a menos
que o tipo seja definido como imutável. A palavra-reservada new pode ser usada para
criar um objeto do mesmo tipo.
Os parâmetros de tipo são invariantes, que significa que Ponto{Float64} <: Ponto{Real} é
falso, embora Float64 <: Real.
Tipos de tupla, por outro lado, são covariantes: Tuple{Float64} <: Tuple{Real}.
A forma inferida de tipo da representação interna de Julia’s pode ser encontrada
com code_typed(). Isso é útil para identificar onde é gerado o código nativo Any e não o tipo específico.
| Programmers Null | nothing |
| Missing Data | missing |
| Not a Number in Float | NaN |
| Filter missings | skipmissing([1, 2, missing]) == [1,2] |
| Replace missings | collect((df[:col], 1)) |
| Check if missing | ismissing(x) not x == missing |
| Lançar AlgumaExcecao | throw(AlgumaExcecao()) |
| Relançar exceção atual | rethrow() |
| Definir NovaExcecao | struct NovaExcecao <: Exception v::StringendBase.showerror(io::IO, e::NovaExcecao) = print(io, "Um problema com $(e.v)!")throw(NovaExcecao("x")) |
| Lançar erro com mensagem | error(mensagem) |
| Tratamento | try # faca algo potencialmente duvidosocatch ex if isa(ex, AlgumaExcecao) # tratar AlgumaExcecao elseif isa(ex, UmaOutraExcecao) # tratar UmaOutraExcecao else # tratar os restantes endfinally # faça isso em qualquer casoend |
Módulos são espaços de trabalho de variáveis globais separados que agrupam funcionalidades semelhantes.
| Definição | module NomeDoPacote# adicionar definições de módulo# usar export para tornar as definições acessíveisend |
Incluir nome_do_arquivo.jl |
include("nome_do_arquivo.jl") |
| Carregar | using NomeDoModulo # todos os nomes exportadosusing NomeDoModulo: x, y # apenas x, yusing NomeDoModulo.x, NomeDoModulo.y: # apenas x, yimport NomeDoModulo # apenas NomeDoModuloimport NomeDoModulo: x, y # apenas x, yimport NomeDoModulo.x, NomeDoModulo.y # apenas x, y |
| Exportações | # Obter uma lista de nomes exportados pelo Módulonames(NomeDoModulo)# incluir nomes não exportados, depreciados# e gerados pelo compiladornames(NomeDoModulo, all::Bool)# também mostra nomes explicitamente importados de outros módulosnames(NomeDoModulo, all::Bool, imported::Bool) |
Existe apenas uma diferença entre using e import : com using você precisa dizer
function Foo.bar(.. para disponibilizar a função bar do módulo Foo’s por meio de um novo método, mas com import Foo.bar, você só precisa dizer function bar(... e ele automaticamente disponibiliza a função bar do módulo Foo’s.
Julia é homoicônico: Programas são representados como estruturas de dados
da própria linguaguem. De fato, tudo é uma expressão Expr.
Símbolos são sequências de caracteres internas Apenas uma cópia de cada cadeia de caracteres (imutável) distinta é armazenada. prefixadas com dois pontos. Símbolos são mais eficientes e são tipicamente utilizados como identificadores, chaves (em dicionários), ou colunas em data frames. Símbolos não podem ser concatenados.
Citação :( ... ) ou quote ... end cria uma expressão, como
parse(str) Essa forma é provavelmente a mais familiar
às pessoas com conhecimentos em SQL dinâmico. A função parse é similiar à declaração
EXECUTE IMMEDIATE da Oracle e da PostgreSQL ou do procedimento sp_executesql() do SQL server·
e Expr(:call, ...).
x = 1
line = "1 + $x" # algum código
expr = parse(line) # Cria um objeto de expressão (Expr)
typeof(expr) == Expr # Verdadeiro
dump(expr) # Gera uma árvore de sintaxes abstratas
eval(expr) == 2 # Avalia um objeto Expr se é verdadeiro
Macros permite que códigos gerados (i.e. expressões) sejam incluídos em um programa.
| Definição | macro nome_do_macro(expr)# comandosend |
| Uso | nome_do_macro(ex1, ex2, ...) or @nome_do_macro ex1, ex2, ... |
| Macros Embutídas | @test # igual (exato)@test_approx_eq # igual (a menos de erros numéricos)@test x ≈ y # isapprox(x, y)@assert # garante afirmação (teste unitário)@which # tipos usados@time # estatísticas de tempo e memória @elapsed # tempo decorrido@allocated # memória alocada@profile # perfil@spawn # executar em algum worker@spawnat #executar num worker específico@async # tarefa assíncrona@distributed # laço for paralelo@everywhere # disponibilizar aos workers |
Regras para criar macros higiênicos:
local .eval dentro do macro.$(esc(expr))Parallel computing tools are available in the Distributed standard library.
| Launch REPL with N workers | julia -p N |
| Number of available workers | nprocs() |
| Add N workers | addprocs(N) |
| See all worker ids | for pid in workers()println(pid)end |
| Get id of executing worker | myid() |
| Remove worker | rmprocs(pid) |
| Run f with arguments args on pid | r = remotecall(f, pid, args...)# or:r = @spawnat pid f(args)...fetch(r) |
| Run f with arguments args on pid (more efficient) | remotecall_fetch(f, pid, args...) |
| Run f with arguments args on any worker | r = @spawn f(args) ... fetch(r) |
| Run f with arguments args on all workers | r = [@spawnat w f(args) for w in workers()] ... fetch(r) |
| Make expr available to all workers | @everywhere expr |
| Parallel for loop with reducerA reducer combines the results from different (independent) workers. function red | sum = @distributed (red) for i in 1:10^6# do parallelstuffend |
| Apply f to all elements in collection coll | pmap(f, coll) |
Workers are also known as concurrent/parallel processes.
Modules with parallel processing capabilities are best split into a functions file that contains all the functions and variables needed by all workers, and a driver file that handles the processing of data. The driver file obviously has to import the functions file.
A non-trivial (word count) example of a reducer function is provided by Adam DeConinck.
| Ler fluxo de dado | stream = stdinfor line in eachline(stream)# faça alguma coisaend |
| Ler arquivo | open(filename) do filefor line in eachline(file)# faça alguma coisaendend |
| Ler arquivo CSV | using CSVCSV.read(filename) |
| Salvar objeto do Julia | using JLDsave(filename, "object_key", object, ...) |
| Carregar objeto do Julia | using JLDd = load(filename) # Retorna um dicionario de objetos |
| Salvar HDF5 | using HDF5h5write(filename, "key", object) |
| Carregar HDF5 | using HDF5h5read(filename, "key") |
For dplyr-like tools, see
DataFramesMeta.jl.
| Read CSV | using CSVCSV.read(filename) |
| Write CSV | using CSVCSV.write(filename) |
| Read Stata, SPSS, etc. | StatFiles Package |
DescribeSimilar to summary(df) in R. data frame |
describe(df) |
Make vector of column col |
v = df[:col] |
Sort by col |
sort!(df, [:col]) |
CategoricalSimilar to df$col = as.factor(df$col) in R. col |
categorical!(df, [:col]) |
List col levels |
levels(df[:col]) |
All observations with col==val |
df[df[:col] .== val, :] |
| Reshape from wide to long format | stack(df, [1:n; ])stack(df, [:col1, :col2, ...])melt(df, [:col1, :col2]) |
| Reshape from long to wide format | unstack(df, :id, :val) |
Make Nullable |
allowmissing!(df) or allowmissing!(df, :col) |
| Loop over Rows | for r in eachrow(df)# do stuff.# r is Struct with fields of col names.end |
| Loop over Columns | for c in eachcol(df)# do stuff.# c is tuple with name, then vectorend |
| Apply func to groups | by(df, :group_col, func) |
| Query | using Queryquery = @from r in df begin@where r.col1 > 40@select {new_name=r.col1, r.col2}@collect DataFrame #Default: iteratorend |
| Type | typeof(name) |
| Type check | isa(name, TypeName) |
| List subtypes | subtypes(name) |
| List supertype | super(TypeName) |
| Function methods | methods(func) |
| JIT bytecode | code_llvm(expr) |
| Assembly code | code_native(expr) |
Many core packages are managed by communities with names of the form Julia[Topic].
| Statistics | JuliaStats |
| Automatic differentiation | JuliaDiff |
| Numerical optimization | JuliaOpt |
| Plotting | JuliaPlots |
| Network (Graph) Analysis | JuliaGraphs |
| Web | JuliaWeb |
| Geo-Spatial | JuliaGeo |
| Machine Learning | JuliaML |
| Super-used Packages | DataFrames # linear/logistic regressionDistributions # Statistical distributionsFlux # Machine learningGadfly # ggplot2-likeplottingLightGraphs # Network analysisTextAnalysis # NLP |
A principal convenção em Julia é evitar sublinhados (_), a menos que seja requirido por legibilidade.
Nomes de variáveis são minúsculas: algumavariavel.
Constantes em maiúsculo: ALGUMACONSTANTE.
Funções em minúsculo: algumafuncao.
Macros em minúsculos: @algumamacro.
Nomes de tipo são da forma: AlgumTipo.
Arquivos em Julia possuem uma extensão jl.
Para mais informações de estilo de código do Julia, visite o manual: guia de estilos.
sizehint for large arrays.arr = nothing.disable_gc()....) operator for keyword arguments.! to avoid copying data structures.try-catch in (computation-intensive) loops.Any in collections.eval at run-time.