mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-01 04:20:39 +02:00
[julia/*] highlight as julia
This commit is contained in:
@@ -9,9 +9,7 @@ filename: learnjulia-es.jl
|
|||||||
lang: es-es
|
lang: es-es
|
||||||
---
|
---
|
||||||
|
|
||||||

|
[Julia](https://julialang.org/) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org).
|
||||||
|
|
||||||
[Julia](http://julialanges.github.io) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org).
|
|
||||||
|
|
||||||
En Julia los programas están organizados entorno al [despacho múltiple](http://docs.julialang.org/en/release-0.3/manual/methods/#man-methods); definiendo funciones y sobrecargándolas para diferentes combinaciones de tipos de argumentos, los cuales también pueden ser definidos por el usuario.
|
En Julia los programas están organizados entorno al [despacho múltiple](http://docs.julialang.org/en/release-0.3/manual/methods/#man-methods); definiendo funciones y sobrecargándolas para diferentes combinaciones de tipos de argumentos, los cuales también pueden ser definidos por el usuario.
|
||||||
|
|
||||||
@@ -41,7 +39,7 @@ En Julia los programas están organizados entorno al [despacho múltiple](http:/
|
|||||||
|
|
||||||
Esto se basa en la versión `0.3.11`.
|
Esto se basa en la versión `0.3.11`.
|
||||||
|
|
||||||
```ruby
|
```julia
|
||||||
# Los comentarios de una línea comienzan con una almohadilla (o signo de gato).
|
# Los comentarios de una línea comienzan con una almohadilla (o signo de gato).
|
||||||
|
|
||||||
#=
|
#=
|
||||||
@@ -931,8 +929,6 @@ code_native(area_circulo, (Float64,))
|
|||||||
=#
|
=#
|
||||||
```
|
```
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## ¿Listo para más?
|
## ¿Listo para más?
|
||||||
|
|
||||||
Para más detalles, lee el [manual de Julia](http://docs.julialang.org/en/release-0.3).
|
Para más detalles, lee el [manual de Julia](http://docs.julialang.org/en/release-0.3).
|
||||||
|
@@ -14,7 +14,7 @@ Julia は科学技術計算向けに作られた、同図像性を持った(homo
|
|||||||
|
|
||||||
この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。
|
この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。
|
||||||
|
|
||||||
```ruby
|
```julia
|
||||||
# ハッシュ(シャープ)記号から改行までは単一行コメントとなります。
|
# ハッシュ(シャープ)記号から改行までは単一行コメントとなります。
|
||||||
#= 複数行コメントは、
|
#= 複数行コメントは、
|
||||||
'#=' と '=#' とで囲むことで行えます。
|
'#=' と '=#' とで囲むことで行えます。
|
||||||
|
@@ -12,7 +12,7 @@ Julia é uma linguagem homoicônica funcional focada na computação técnica. A
|
|||||||
|
|
||||||
Este tutorial é baseado no Julia 0.3.
|
Este tutorial é baseado no Julia 0.3.
|
||||||
|
|
||||||
```ruby
|
```julia
|
||||||
# Linhas únicas de comentários começam com o simbolo hash(jogo da velha).
|
# Linhas únicas de comentários começam com o simbolo hash(jogo da velha).
|
||||||
#= Comentários de multiplas linhas podem ser escritos
|
#= Comentários de multiplas linhas podem ser escritos
|
||||||
colocando '#=' antes do texto e '=#'
|
colocando '#=' antes do texto e '=#'
|
||||||
@@ -88,7 +88,7 @@ false
|
|||||||
# Uma string pode ser indexada como um vetor de caracteres
|
# Uma string pode ser indexada como um vetor de caracteres
|
||||||
"Isso é uma string"[1] # => 'I' # Julia começa a indexar a partir do 1
|
"Isso é uma string"[1] # => 'I' # Julia começa a indexar a partir do 1
|
||||||
# Porém isso não funcionará direito com strings em UTF8,
|
# Porém isso não funcionará direito com strings em UTF8,
|
||||||
# portanto é recomendado usar iterações sobre uma string (map, loops com for, etc).
|
# portanto é recomendado usar iterações sobre uma string (map, loops com for, etc).
|
||||||
|
|
||||||
# $ pode ser usado para interpolação de string:
|
# $ pode ser usado para interpolação de string:
|
||||||
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
|
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
|
||||||
@@ -110,7 +110,7 @@ some_var # => 5
|
|||||||
|
|
||||||
# Acessando a variável anterior não iniciada é um erro
|
# Acessando a variável anterior não iniciada é um erro
|
||||||
try
|
try
|
||||||
some_other_var # => ERROR: some_other_var não definida
|
some_other_var # => ERROR: some_other_var não definida
|
||||||
catch e
|
catch e
|
||||||
println(e)
|
println(e)
|
||||||
end
|
end
|
||||||
@@ -130,7 +130,7 @@ SomeOtherVar123! = 6 # => 6
|
|||||||
# de underscore é desencorajado a menos que o nome da variável seja dificil
|
# de underscore é desencorajado a menos que o nome da variável seja dificil
|
||||||
# de ler.
|
# de ler.
|
||||||
#
|
#
|
||||||
# * Os nomes de tipos começam com letra maiúscula e a separação de letras é
|
# * Os nomes de tipos começam com letra maiúscula e a separação de letras é
|
||||||
# feita a partir de CamelCase no lugar de underscores.
|
# feita a partir de CamelCase no lugar de underscores.
|
||||||
#
|
#
|
||||||
# * Nomes de funções e macros são em minúsculo, sem underscore.
|
# * Nomes de funções e macros são em minúsculo, sem underscore.
|
||||||
@@ -186,8 +186,8 @@ catch e
|
|||||||
println(e)
|
println(e)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Erros listam a linha e o nome do arquivo que ele está, mesmo se for uma
|
# Erros listam a linha e o nome do arquivo que ele está, mesmo se for uma
|
||||||
# biblioteca padrão. Se você construiu Julia pelo source, você pode olhar na
|
# biblioteca padrão. Se você construiu Julia pelo source, você pode olhar na
|
||||||
# pasta base dentro da pasta do Julia para encontrar esses arquivos.
|
# pasta base dentro da pasta do Julia para encontrar esses arquivos.
|
||||||
|
|
||||||
# Você pode inicializar vetores com limites
|
# Você pode inicializar vetores com limites
|
||||||
@@ -315,7 +315,7 @@ end
|
|||||||
# Tipos iterativos incluem Range, Array, set Dict e String.
|
# Tipos iterativos incluem Range, Array, set Dict e String.
|
||||||
for animal=["dog", "cat", "mouse"]
|
for animal=["dog", "cat", "mouse"]
|
||||||
println("$animal is a mammal")
|
println("$animal is a mammal")
|
||||||
# Você pode interpolar variáveis usando $ ou expressões em strings
|
# Você pode interpolar variáveis usando $ ou expressões em strings
|
||||||
end
|
end
|
||||||
# exibe:
|
# exibe:
|
||||||
# dog is a mammal
|
# dog is a mammal
|
||||||
@@ -379,14 +379,14 @@ end
|
|||||||
function add(x, y)
|
function add(x, y)
|
||||||
println("x is $x and y is $y")
|
println("x is $x and y is $y")
|
||||||
|
|
||||||
# Funções retornam o valor da sua ultima declaração
|
# Funções retornam o valor da sua ultima declaração
|
||||||
t x + y
|
t x + y
|
||||||
end
|
end
|
||||||
|
|
||||||
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
|
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
|
||||||
|
|
||||||
# Você pode definir funções que tomam um numero incerto de
|
# Você pode definir funções que tomam um numero incerto de
|
||||||
# argumentos
|
# argumentos
|
||||||
function varargs(args...)
|
function varargs(args...)
|
||||||
return args
|
return args
|
||||||
# use a palavra chave return para retornar um valor em qualquer parte da função
|
# use a palavra chave return para retornar um valor em qualquer parte da função
|
||||||
@@ -471,7 +471,7 @@ add_10 = create_adder(10)
|
|||||||
add_10(3) # => 13
|
add_10(3) # => 13
|
||||||
|
|
||||||
|
|
||||||
# Há
|
# Há
|
||||||
# There are built-in higher order functions
|
# There are built-in higher order functions
|
||||||
map(add_10, [1,2,3]) # => [11, 12, 13]
|
map(add_10, [1,2,3]) # => [11, 12, 13]
|
||||||
filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||||
@@ -672,7 +672,7 @@ square_area(5) #25
|
|||||||
|
|
||||||
# O que acontece quando alimentamos square_area com um inteiro?
|
# O que acontece quando alimentamos square_area com um inteiro?
|
||||||
# What happens when we feed square_area an integer?
|
# What happens when we feed square_area an integer?
|
||||||
code_native(square_area, (Int32,))
|
code_native(square_area, (Int32,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1 # Prólogo
|
# Source line: 1 # Prólogo
|
||||||
@@ -705,7 +705,7 @@ code_native(square_area, (Float64,))
|
|||||||
# vmulsd XMM0, XMM0, XMM0 # Duplicação ecalar de precisão multipla(AVX)
|
# vmulsd XMM0, XMM0, XMM0 # Duplicação ecalar de precisão multipla(AVX)
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
# Note que Julia usará instruções de ponto flutuante se quaser um dos
|
# Note que Julia usará instruções de ponto flutuante se quaser um dos
|
||||||
# argumentos forem float
|
# argumentos forem float
|
||||||
# Vamos calcular a área de um circulo
|
# Vamos calcular a área de um circulo
|
||||||
@@ -739,10 +739,10 @@ code_native(circle_area, (Float64,))
|
|||||||
# vmulsd XMM0, XMM1, XMM0
|
# vmulsd XMM0, XMM1, XMM0
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
```
|
```
|
||||||
|
|
||||||
## Extras
|
## Extras
|
||||||
|
|
||||||
Você pode ver mais um monte de detalhes no [manual de Julia] (http://docs.julialang.org/en/latest/manual/)
|
Você pode ver mais um monte de detalhes no [manual de Julia](http://docs.julialang.org/en/latest/manual/)
|
||||||
O melhor lugar pra pedir ajuda em Julia é a (muito amigável) [mailing list](https://groups.google.com/forum/#!forum/julia-users).
|
O melhor lugar pra pedir ajuda em Julia é a (muito amigável) [mailing list](https://groups.google.com/forum/#!forum/julia-users).
|
||||||
|
@@ -13,7 +13,7 @@ Julia — гомоиконный функциональный язык прог
|
|||||||
|
|
||||||
Документ описывает текущую dev-версию Julia от 18-о октября 2013 года.
|
Документ описывает текущую dev-версию Julia от 18-о октября 2013 года.
|
||||||
|
|
||||||
```ruby
|
```julia
|
||||||
# Однострочные комментарии начинаются со знака решётки.
|
# Однострочные комментарии начинаются со знака решётки.
|
||||||
|
|
||||||
####################################################
|
####################################################
|
||||||
@@ -113,7 +113,7 @@ catch e
|
|||||||
end
|
end
|
||||||
|
|
||||||
# Имена переменных начинаются с букв.
|
# Имена переменных начинаются с букв.
|
||||||
# После первого символа можно использовать буквы, цифры,
|
# После первого символа можно использовать буквы, цифры,
|
||||||
# символы подчёркивания и восклицательные знаки.
|
# символы подчёркивания и восклицательные знаки.
|
||||||
SomeOtherVar123! = 6 # => 6
|
SomeOtherVar123! = 6 # => 6
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ SomeOtherVar123! = 6 # => 6
|
|||||||
2 * π # => 6.283185307179586
|
2 * π # => 6.283185307179586
|
||||||
|
|
||||||
# Рекомендации по именованию:
|
# Рекомендации по именованию:
|
||||||
# * имена переменных в нижнем регистре, слова разделяются символом
|
# * имена переменных в нижнем регистре, слова разделяются символом
|
||||||
# подчёркивания ('\_');
|
# подчёркивания ('\_');
|
||||||
#
|
#
|
||||||
# * для имён типов используется CamelCase;
|
# * для имён типов используется CamelCase;
|
||||||
@@ -184,7 +184,7 @@ end
|
|||||||
|
|
||||||
# Вывод ошибок содержит строку и файл, где произошла ошибка,
|
# Вывод ошибок содержит строку и файл, где произошла ошибка,
|
||||||
# даже если это случилось в стандартной библиотеке.
|
# даже если это случилось в стандартной библиотеке.
|
||||||
# Если вы собрали Julia из исходных кодов,
|
# Если вы собрали Julia из исходных кодов,
|
||||||
# то найти эти файлы можно в директории base.
|
# то найти эти файлы можно в директории base.
|
||||||
|
|
||||||
# Создавать массивы можно из последовательности
|
# Создавать массивы можно из последовательности
|
||||||
@@ -445,7 +445,7 @@ all_the_args(1, 3, keyword_arg=4)
|
|||||||
# optional arg: 3
|
# optional arg: 3
|
||||||
# keyword arg: 4
|
# keyword arg: 4
|
||||||
|
|
||||||
# Функции в Julia первого класса
|
# Функции в Julia первого класса
|
||||||
function create_adder(x)
|
function create_adder(x)
|
||||||
adder = function (y)
|
adder = function (y)
|
||||||
return x + y
|
return x + y
|
||||||
@@ -526,7 +526,7 @@ sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire")
|
|||||||
# abstract Name
|
# abstract Name
|
||||||
abstract Cat # просто имя и точка в иерархии типов
|
abstract Cat # просто имя и точка в иерархии типов
|
||||||
|
|
||||||
# Объекты абстрактных типов создавать нельзя,
|
# Объекты абстрактных типов создавать нельзя,
|
||||||
# но зато от них можно наследовать подтипы.
|
# но зато от них можно наследовать подтипы.
|
||||||
# Например, Number — это абстрактный тип.
|
# Например, Number — это абстрактный тип.
|
||||||
subtypes(Number) # => 6 элементов в массиве Array{Any,1}:
|
subtypes(Number) # => 6 элементов в массиве Array{Any,1}:
|
||||||
@@ -672,40 +672,40 @@ square_area(l) = l * l # square_area (generic function with 1 method)
|
|||||||
square_area(5) #25
|
square_area(5) #25
|
||||||
|
|
||||||
# Что происходит, когда мы передаём функции square_area целое число?
|
# Что происходит, когда мы передаём функции square_area целое число?
|
||||||
code_native(square_area, (Int32,))
|
code_native(square_area, (Int32,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1 # Вводная часть
|
# Source line: 1 # Вводная часть
|
||||||
# push RBP
|
# push RBP
|
||||||
# mov RBP, RSP
|
# mov RBP, RSP
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# movsxd RAX, EDI #
|
# movsxd RAX, EDI #
|
||||||
# imul RAX, RAX #
|
# imul RAX, RAX #
|
||||||
# pop RBP #
|
# pop RBP #
|
||||||
# ret #
|
# ret #
|
||||||
|
|
||||||
code_native(square_area, (Float32,))
|
code_native(square_area, (Float32,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# push RBP
|
# push RBP
|
||||||
# mov RBP, RSP
|
# mov RBP, RSP
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# vmulss XMM0, XMM0, XMM0 # Произведение чисел одинарной точности (AVX)
|
# vmulss XMM0, XMM0, XMM0 # Произведение чисел одинарной точности (AVX)
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
|
|
||||||
code_native(square_area, (Float64,))
|
code_native(square_area, (Float64,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# push RBP
|
# push RBP
|
||||||
# mov RBP, RSP
|
# mov RBP, RSP
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# vmulsd XMM0, XMM0, XMM0 # Произведение чисел двойной точности (AVX)
|
# vmulsd XMM0, XMM0, XMM0 # Произведение чисел двойной точности (AVX)
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
# Если хотя бы один из аргументов является числом с плавающей запятой,
|
# Если хотя бы один из аргументов является числом с плавающей запятой,
|
||||||
# то Julia будет использовать соответствующие инструкции.
|
# то Julia будет использовать соответствующие инструкции.
|
||||||
# Вычислим площать круга
|
# Вычислим площать круга
|
||||||
@@ -713,33 +713,33 @@ circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
|
|||||||
circle_area(5) # 78.53981633974483
|
circle_area(5) # 78.53981633974483
|
||||||
|
|
||||||
code_native(circle_area, (Int32,))
|
code_native(circle_area, (Int32,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# push RBP
|
# push RBP
|
||||||
# mov RBP, RSP
|
# mov RBP, RSP
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# vcvtsi2sd XMM0, XMM0, EDI # Загрузить целое число (r)
|
# vcvtsi2sd XMM0, XMM0, EDI # Загрузить целое число (r)
|
||||||
# movabs RAX, 4593140240 # Загрузить pi
|
# movabs RAX, 4593140240 # Загрузить pi
|
||||||
# vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r
|
# vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r
|
||||||
# vmulsd XMM0, XMM0, XMM1 # (pi * r) * r
|
# vmulsd XMM0, XMM0, XMM1 # (pi * r) * r
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
|
|
||||||
code_native(circle_area, (Float64,))
|
code_native(circle_area, (Float64,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# push RBP
|
# push RBP
|
||||||
# mov RBP, RSP
|
# mov RBP, RSP
|
||||||
# movabs RAX, 4593140496
|
# movabs RAX, 4593140496
|
||||||
# Source line: 1
|
# Source line: 1
|
||||||
# vmulsd XMM1, XMM0, QWORD PTR [RAX]
|
# vmulsd XMM1, XMM0, QWORD PTR [RAX]
|
||||||
# vmulsd XMM0, XMM1, XMM0
|
# vmulsd XMM0, XMM1, XMM0
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
```
|
```
|
||||||
|
|
||||||
## Что дальше?
|
## Что дальше?
|
||||||
|
@@ -93,7 +93,7 @@ false
|
|||||||
# 字符串使用 UTF-8 编码
|
# 字符串使用 UTF-8 编码
|
||||||
# 可以像取数组取值一样用 index 取出对应字符
|
# 可以像取数组取值一样用 index 取出对应字符
|
||||||
ascii("This is a string")[1]
|
ascii("This is a string")[1]
|
||||||
# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase)
|
# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase)
|
||||||
# Julia 的 index 从 1 开始 :(
|
# Julia 的 index 从 1 开始 :(
|
||||||
# 但只有在字符串仅由 ASCII 字符构成时,字符串才能够被安全的引索
|
# 但只有在字符串仅由 ASCII 字符构成时,字符串才能够被安全的引索
|
||||||
# 因此建议使用遍历器 (map, for loops, 等)
|
# 因此建议使用遍历器 (map, for loops, 等)
|
||||||
@@ -186,7 +186,7 @@ a[1] # => 1 # 永远记住 Julia 的引索从 1 开始!而不是 0!
|
|||||||
a[end] # => 6
|
a[end] # => 6
|
||||||
|
|
||||||
# 数组还支持 popfirst! 和 pushfirst!
|
# 数组还支持 popfirst! 和 pushfirst!
|
||||||
popfirst!(a) # => 1
|
popfirst!(a) # => 1
|
||||||
a # => [2,4,3,4,5,6]
|
a # => [2,4,3,4,5,6]
|
||||||
pushfirst!(a, 7) # => [7,2,4,3,4,5,6]
|
pushfirst!(a, 7) # => [7,2,4,3,4,5,6]
|
||||||
a # => [7,2,4,3,4,5,6]
|
a # => [7,2,4,3,4,5,6]
|
||||||
@@ -200,16 +200,16 @@ arr # => [4,5,6]
|
|||||||
|
|
||||||
# 数组越界会抛出 BoundsError
|
# 数组越界会抛出 BoundsError
|
||||||
try
|
try
|
||||||
a[0]
|
a[0]
|
||||||
# => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at
|
# => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at
|
||||||
# index [0]
|
# index [0]
|
||||||
# => Stacktrace:
|
# => Stacktrace:
|
||||||
# => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731
|
# => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731
|
||||||
# => [2] top-level scope at none:0
|
# => [2] top-level scope at none:0
|
||||||
# => [3] ...
|
# => [3] ...
|
||||||
# => in expression starting at ...\LearnJulia.jl:203
|
# => in expression starting at ...\LearnJulia.jl:203
|
||||||
a[end + 1]
|
a[end + 1]
|
||||||
# => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at
|
# => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at
|
||||||
# index [8]
|
# index [8]
|
||||||
# => Stacktrace:
|
# => Stacktrace:
|
||||||
# => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731
|
# => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731
|
||||||
@@ -234,7 +234,7 @@ a[2:end] # => [2, 3, 4, 5]
|
|||||||
|
|
||||||
# 用 splice! 切割原数组
|
# 用 splice! 切割原数组
|
||||||
arr = [3,4,5]
|
arr = [3,4,5]
|
||||||
splice!(arr, 2) # => 4
|
splice!(arr, 2) # => 4
|
||||||
arr # => [3,5]
|
arr # => [3,5]
|
||||||
|
|
||||||
# 用 append! 连接数组
|
# 用 append! 连接数组
|
||||||
@@ -253,8 +253,8 @@ tup = (1, 2, 3) # => (1,2,3)
|
|||||||
typeof(tup) # => Tuple{Int64,Int64,Int64}
|
typeof(tup) # => Tuple{Int64,Int64,Int64}
|
||||||
tup[1] # => 1
|
tup[1] # => 1
|
||||||
try
|
try
|
||||||
tup[1] = 3
|
tup[1] = 3
|
||||||
# => ERROR: MethodError: no method matching
|
# => ERROR: MethodError: no method matching
|
||||||
# setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64)
|
# setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64)
|
||||||
catch e
|
catch e
|
||||||
println(e)
|
println(e)
|
||||||
@@ -266,7 +266,7 @@ tup[1:2] # => (1,2)
|
|||||||
in(2, tup) # => true
|
in(2, tup) # => true
|
||||||
|
|
||||||
# 可以将元组的元素解包赋给变量
|
# 可以将元组的元素解包赋给变量
|
||||||
a, b, c = (1, 2, 3) # => (1,2,3)
|
a, b, c = (1, 2, 3) # => (1,2,3)
|
||||||
a # => 1
|
a # => 1
|
||||||
b # => 2
|
b # => 2
|
||||||
c # => 3
|
c # => 3
|
||||||
@@ -282,7 +282,7 @@ f # => 6
|
|||||||
(1) == 1 # => true
|
(1) == 1 # => true
|
||||||
|
|
||||||
# 交换值
|
# 交换值
|
||||||
e, d = d, e # => (5,4)
|
e, d = d, e # => (5,4)
|
||||||
d # => 5
|
d # => 5
|
||||||
e # => 4
|
e # => 4
|
||||||
|
|
||||||
@@ -306,7 +306,7 @@ keys(filled_dict)
|
|||||||
|
|
||||||
# 获得所有值
|
# 获得所有值
|
||||||
values(filled_dict)
|
values(filled_dict)
|
||||||
# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values:
|
# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values:
|
||||||
# => 2, 1, 3
|
# => 2, 1, 3
|
||||||
# 注意,值的顺序也一样
|
# 注意,值的顺序也一样
|
||||||
|
|
||||||
@@ -368,7 +368,7 @@ end
|
|||||||
# 可迭代的类型包括:Range, Array, Set, Dict 和 AbstractString
|
# 可迭代的类型包括:Range, Array, Set, Dict 和 AbstractString
|
||||||
for animal = ["dog", "cat", "mouse"]
|
for animal = ["dog", "cat", "mouse"]
|
||||||
println("$animal is a mammal")
|
println("$animal is a mammal")
|
||||||
# 你可以用 $ 将变量或表达式插入字符串中
|
# 你可以用 $ 将变量或表达式插入字符串中
|
||||||
end
|
end
|
||||||
# => dog is a mammal
|
# => dog is a mammal
|
||||||
# => cat is a mammal
|
# => cat is a mammal
|
||||||
@@ -528,7 +528,7 @@ function create_adder(x)
|
|||||||
end
|
end
|
||||||
# => create_adder (generic function with 1 method)
|
# => create_adder (generic function with 1 method)
|
||||||
|
|
||||||
add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64})
|
add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64})
|
||||||
# (generic function with 1 method)
|
# (generic function with 1 method)
|
||||||
add_10(3) # => 13
|
add_10(3) # => 13
|
||||||
|
|
||||||
@@ -707,7 +707,7 @@ fight(l::Lion, c::Cat) = println("The victorious cat says $(meow(c))")
|
|||||||
|
|
||||||
fight(Lion("balooga!"), Panther()) # => The victorious cat says grrr
|
fight(Lion("balooga!"), Panther()) # => The victorious cat says grrr
|
||||||
try
|
try
|
||||||
fight(Panther(), Lion("RAWR"))
|
fight(Panther(), Lion("RAWR"))
|
||||||
# => ERROR: MethodError: no method matching fight(::Panther, ::Lion)
|
# => ERROR: MethodError: no method matching fight(::Panther, ::Lion)
|
||||||
# => Closest candidates are:
|
# => Closest candidates are:
|
||||||
# => fight(::Tiger, ::Lion) at ...
|
# => fight(::Tiger, ::Lion) at ...
|
||||||
@@ -736,7 +736,7 @@ catch e
|
|||||||
end
|
end
|
||||||
# 在不同版本的 Julia 中错误信息可能有所不同
|
# 在不同版本的 Julia 中错误信息可能有所不同
|
||||||
|
|
||||||
fight(l::Lion, l2::Lion) = println("The lions come to a tie")
|
fight(l::Lion, l2::Lion) = println("The lions come to a tie")
|
||||||
# => fight (generic function with 5 methods)
|
# => fight (generic function with 5 methods)
|
||||||
fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie
|
fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie
|
||||||
|
|
||||||
@@ -749,20 +749,20 @@ square_area(5) # => 25
|
|||||||
|
|
||||||
# 当我们喂给 square_area 一个整数时会发生什么?
|
# 当我们喂给 square_area 一个整数时会发生什么?
|
||||||
code_native(square_area, (Int32,), syntax = :intel)
|
code_native(square_area, (Int32,), syntax = :intel)
|
||||||
# .text
|
# .text
|
||||||
# ; Function square_area {
|
# ; Function square_area {
|
||||||
# ; Location: REPL[116]:1 # 函数序言 (Prologue)
|
# ; Location: REPL[116]:1 # 函数序言 (Prologue)
|
||||||
# push rbp
|
# push rbp
|
||||||
# mov rbp, rsp
|
# mov rbp, rsp
|
||||||
# ; Function *; {
|
# ; Function *; {
|
||||||
# ; Location: int.jl:54
|
# ; Location: int.jl:54
|
||||||
# imul ecx, ecx # 求 l 的平方,并把结果放在 ECX 中
|
# imul ecx, ecx # 求 l 的平方,并把结果放在 ECX 中
|
||||||
# ;}
|
# ;}
|
||||||
# mov eax, ecx
|
# mov eax, ecx
|
||||||
# pop rbp # 还原旧的基址指针(base pointer)
|
# pop rbp # 还原旧的基址指针(base pointer)
|
||||||
# ret # 返回值放在 EAX 中
|
# ret # 返回值放在 EAX 中
|
||||||
# nop dword ptr [rax + rax]
|
# nop dword ptr [rax + rax]
|
||||||
# ;}
|
# ;}
|
||||||
# 使用 syntax 参数指定输出语法。默认为 AT&T 格式,这里指定为 Intel 格式
|
# 使用 syntax 参数指定输出语法。默认为 AT&T 格式,这里指定为 Intel 格式
|
||||||
|
|
||||||
code_native(square_area, (Float32,), syntax = :intel)
|
code_native(square_area, (Float32,), syntax = :intel)
|
||||||
|
Reference in New Issue
Block a user