Skip to content

Julia Hoja de referencia

Julia es un lenguaje dinámico de alto nivel y alto rendimiento para computación técnica.

01

Fundamentos

Hello World

println agrega un salto de línea, print no lo hace

julia
println("Hello, World!")
print("No newline")

Comentarios

#= =# para comentarios multilínea

julia
# Single-line comment

#=
  Multi-line
  comment
=#

# Docstring
"""docstring"""

REPL

ans guarda el resultado anterior

julia
$ julia
julia> 1 + 1
2
julia> ans  # previous result
2

Interpolación de cadenas

$ para variables, $(expression) para expresiones

julia
name = "Alice"
age = 30
println("$name is $age")
println("$(age * 2)")

Comparaciones encadenadas

Julia admite comparaciones encadenadas

julia
x = 5
1 < x < 10  # true
1 <= x <= 10  # true
02

Variables

Asignación de variables

Admite nombres de variables Unicode

julia
x = 10
name = "Alice"
π = 3.14159  # supports Unicode
δ = 0.001

Constantes

const declara una constante global

julia
const PI = 3.14159
const MAX_SIZE = 100
# const declares a constant

Anotaciones de tipo

:: para anotaciones de tipo

julia
x::Int = 10
y::Float64 = 3.14
function f(x::Int)::String
  string(x)
end

Asignación múltiple

Admite asignación múltiple

julia
a, b, c = 1, 2, 3
x, y = y, x  # swap
(a, b) = (1, 2)
03

Tipos

Tipos básicos

typeof obtiene el tipo

julia
typeof(42)       # Int64
typeof(3.14)     # Float64
typeof("hi")     # String
typeof(true)     # Bool
typeof('a')      # Char

Conversión de tipos

Usa el nombre del tipo como función de conversión

julia
Int(3.14)    # 3
Float64(3)   # 3.0
String(42)   # "42"
Char(65)     # 'A'

Tipos abstractos

abstract type define un tipo abstracto

julia
abstract type Animal end
abstract type Dog <: Animal end
# <: denotes subtype relationship

Structs

struct es inmutable

julia
struct Point
  x::Float64
  y::Float64
end

p = Point(1.0, 2.0)
p.x  # 1.0

Structs mutables

mutable struct permite modificar los campos

julia
mutable struct Counter
  count::Int
end

c = Counter(0)
c.count += 1

Tipos paramétricos

T es un parámetro de tipo

julia
struct Point{T}
  x::T
  y::T
end

p = Point{Float64}(1.0, 2.0)
q = Point{Int}(1, 2)
04

Despacho múltiple

Sobrecarga de funciones

Característica central de Julia: el multiple dispatch

julia
function describe(x::Int)
  "integer: $x"
end

function describe(x::String)
  "string: $x"
end

describe(42)      # "integer: 42"
describe("hi")    # "string: hi"

Funciones paramétricas

where especifica los parámetros de tipo

julia
function norm(p::Point{T}) where T
  sqrt(p.x^2 + p.y^2)
end

# Works for all types T

Funciones de respaldo

Una función sin anotaciones de tipo actúa como predeterminada

julia
function describe(x)
  "unknown: $x"
end

# No type annotation, matches all arguments

Ambigüedad de funciones

Ten cuidado de evitar la ambigüedad entre funciones

julia
f(x::Int, y) = 1
f(x, y::Int) = 2
# f(1, 1) raises an ambiguity error
# Need to define f(x::Int, y::Int) = 3
05

Funciones

Definición de funciones

return es opcional; se devuelve la última expresión

julia
function add(a, b)
  return a + b
end

# Shorthand
add(a, b) = a + b

Funciones anónimas

-> define una función anónima

julia
f = x -> x^2
f(5)  # 25

map(x -> x * 2, [1, 2, 3])

Múltiples valores de retorno

Devuelve una tupla para varios valores

julia
function divrem2(a, b)
  return a ÷ b, a % b
end

q, r = divrem2(10, 3)

Argumentos por palabra clave

Después de ; van los argumentos por palabra clave

julia
function plot(x, y; style="line", color="blue")
  # style and color are keyword arguments
end

plot(1:10, 1:10, color="red")

Argumentos variádicos

... agrupa los argumentos variádicos

julia
function sumall(args...)
  sum(args)
end

sumall(1, 2, 3, 4)  # 10

Bloque do

El bloque do pasa una función anónima

julia
map([1, 2, 3]) do x
  x ^ 2
end
# Equivalent to map(x -> x^2, [1,2,3])
06

Flujo de control

if-elseif-else

Expresión condicional

julia
if x > 0
  println("positive")
elseif x < 0
  println("negative")
else
  println("zero")
end

Operador ternario

condición ? true_value : false_value

julia
result = x > 0 ? "pos" : "neg"

# Chained
result = x > 0 ? "pos" : x < 0 ? "neg" : "zero"

Bucle for

for in para iterar

julia
for i in 1:5
  println(i)
end

for (i, v) in enumerate(arr)
  println(i, v)
end

Bucle while

Bucle while

julia
i = 1
while i <= 5
  println(i)
  i += 1
end

break y continue

&& evalúa en cortocircuito para condiciones

julia
for i in 1:10
  i == 5 && break
  i % 2 == 0 && continue
  println(i)
end
07

Arrays

Crear arrays

Los arrays son column-major

julia
a = [1, 2, 3, 4, 5]
b = [1 2 3; 4 5 6]  # 2x3 matrix
c = zeros(3, 3)
d = ones(5)
e = rand(2, 2)

Indexación de arrays

Los índices empiezan en 1

julia
a = [10, 20, 30, 40, 50]
a[1]      # 10 (1-based)
a[end]    # 50
a[2:4]    # [20, 30, 40]
a[[1, 3]] # [10, 30]

Operaciones con arrays

El sufijo ! indica modificación in-place

julia
push!(a, 60)    # add to end
pop!(a)          # remove from end
append!(a, b)    # concatenate
sort(a)          # sort (returns new array)
sort!(a)         # in-place sort

Array comprehensions

Similar a la comprensión de listas

julia
[x^2 for x in 1:5]
# [1, 4, 9, 16, 25]

[x^2 for x in 1:10 if x % 2 == 0]
# [4, 16, 36, 64, 100]

Broadcasting

El operador . para broadcasting

julia
a = [1, 2, 3]
a .^ 2       # [1, 4, 9]
f.(a)        # apply f to each element
a .+ 10      # [11, 12, 13]
08

Tuplas

Tuplas

Las tuplas son inmutables

julia
t = (1, 2, 3)
t[1]  # 1
t[2]  # 2

# Named tuple
nt = (name="Alice", age=30)
nt.name  # "Alice"

Desestructuración

Asignación por desestructuración de tuplas

julia
a, b, c = (1, 2, 3)
(first, second) = (10, 20)

# Ignore
_, y = (1, 2)
09

Diccionarios

Crear diccionarios

Dict crea un diccionario

julia
d = Dict("a" => 1, "b" => 2)
d2 = Dict(:name => "Alice", :age => 30)
d["c"] = 3  # add

Acceso y modificación

[] para acceder y modificar

julia
d = Dict("a" => 1, "b" => 2)
d["a"]      # 1
d["a"] = 10 # modify
delete!(d, "b")  # delete

Iteración

Itera sobre pares clave-valor

julia
for (k, v) in d
  println(k, " => ", v)
end

keys(d)    # all keys
values(d)  # all values

Operaciones con diccionarios

Funciones de diccionario habituales

julia
haskey(d, "a")    # true
get(d, "x", 0)     # default value 0
get!(d, "x", 0)    # add if missing
merge(d1, d2)      # merge
10

Cadenas

Fundamentos de cadenas

Los índices de cadenas pueden ser no contiguos (UTF-8)

julia
s = "Hello World"
length(s)    # 11
s[1]         # 'H'
s[1:5]       # "Hello"
lastindex(s) # 11

Operaciones con cadenas

Funciones de cadena habituales

julia
uppercase("hi")    # "HI"
lowercase("HI")    # "hi"
reverse("hello")   # "olleh"
strip("  hi  ")     # "hi"

Buscar y reemplazar

Buscar y reemplazar

julia
s = "Hello World"
findfirst("World", s)  # 7:11
occursin("World", s)   # true
replace(s, "World" => "Julia")  # "Hello Julia"

Dividir y unir

split y join

julia
split("a,b,c", ",")   # ["a", "b", "c"]
join(["a", "b"], "-")  # "a-b"
split("hello", "")     # ['h','e','l','l','o']
11

Funciones matemáticas

Matemática básica

Funciones matemáticas integradas

julia
abs(-5)      # 5
sqrt(16)    # 4.0
cbrt(27)    # 3.0
sign(-5)    # -1
floor(3.7)  # 3.0
ceil(3.2)   # 4.0

Funciones trigonométricas

En radianes

julia
sin(π/2)   # 1.0
cos(0)     # 1.0
tan(π/4)  # 1.0
asin(1)   # 1.5707... (π/2)

Logaritmo y exponencial

log es el logaritmo natural

julia
log(ℯ)      # 1.0 (natural log)
log2(8)    # 3.0
log10(100) # 2.0
exp(1)     # 2.718... (ℯ)

Valores especiales

Constantes matemáticas y valores especiales

julia
π     # 3.14159...
ℯ     # 2.71828...
Inf   # positive infinity
NaN   # not a number
im    # imaginary unit
12

Álgebra lineal

Operaciones con matrices

Librería estándar LinearAlgebra

julia
using LinearAlgebra

A = [1 2; 3 4]
A'        # transpose
inv(A)    # inverse matrix
det(A)    # determinant
rank(A)   # rank

Descomposición de matrices

Diversas descomposiciones de matrices

julia
A = [1.0 2.0; 3.0 4.0]
F = lu(A)    # LU decomposition
F = qr(A)    # QR decomposition
F = svd(A)   # SVD decomposition
F = eigen(A) # eigendecomposition

Operaciones con vectores

Operaciones con vectores

julia
v1 = [1, 2, 3]
v2 = [4, 5, 6]
dot(v1, v2)    # dot product
cross(v1, v2)  # cross product
norm(v1)       # norm
v1 ⋅ v2       # dot product (Unicode)
13

Estadística

Estadística básica

Librería estándar Statistics

julia
using Statistics

data = [1, 2, 3, 4, 5]
mean(data)    # 3.0
median(data)  # 3.0
std(data)     # standard deviation
var(data)     # variance

Cuantiles

Cálculo de cuantiles

julia
using Statistics

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
quantile(data, 0.25)  # 3.25
quantile(data, 0.5)   # 5.5
quantile(data, 0.75)  # 7.75

Correlación y covarianza

Coeficiente de correlación y covarianza

julia
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cor(x, y)    # 1.0 (correlation coefficient)
cov(x, y)    # covariance
14

Gráficos

Gráficos básicos

Plots.jl es la librería de gráficos principal

julia
using Plots

x = 1:10
y = x .^ 2
plot(x, y, title="Quadratic", label="x^2")

Diagrama de dispersión

scatter dibuja un diagrama de dispersión

julia
using Plots

x = rand(50)
y = rand(50)
scatter(x, y, markersize=5, color=:red)

Subgráficos

layout controla la disposición de los subgráficos

julia
using Plots

p1 = plot(1:10, 1:10)
p2 = plot(1:10, (1:10).^2)
plot(p1, p2, layout=(2, 1))

Guardar imagen

savefig guarda la imagen

julia
using Plots

p = plot(sin, 0, 2π)
savefig(p, "sine.png")
15

DataFrames

Crear un DataFrame

DataFrames.jl es similar a pandas

julia
using DataFrames

df = DataFrame(
  name = ["Alice", "Bob", "Carol"],
  age = [25, 30, 35],
  city = ["NYC", "LA", "SF"]
)

Acceder a los datos

Acceso por filas y columnas

julia
df.name      # column
df[1, :]     # first row
df[:, :age]  # age column
df[1:2, :]   # first two rows

Filtrar y ordenar

Filtrado y ordenamiento

julia
using DataFrames

filter(:age => >(28), df)  # age > 28
sort(df, :age)            # sort by age
sort(df, :age, rev=true)  # descending

Agrupar y agregar

groupby + combine para agregación agrupada

julia
using DataFrames, Statistics

combine(groupby(df, :city), :age => mean => :avg_age)
16

Entrada/salida de archivos

Leer y escribir texto

El bloque open do cierra el archivo automáticamente

julia
# Write
open("output.txt", "w") do f
  write(f, "Hello World")
end

# Read
content = read("input.txt", String)

Leer línea por línea

eachline itera línea por línea

julia
for line in eachline("data.txt")
  println(line)
end

# Or
lines = readlines("data.txt")

Archivos CSV

CSV.jl maneja archivos CSV

julia
using CSV, DataFrames

df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)

Archivos JSON

JSON.jl maneja JSON

julia
using JSON

data = JSON.parsefile("data.json")
JSON.print("output.json", data)
17

Módulos

Definir módulos

export declara la interfaz pública

julia
module MyModule

export greet, add

greet(name) = println("Hello $name")
add(a, b) = a + b

end  # module

Importar módulos

Diferencia entre using e import

julia
using MyModule     # imports exported names
using MyModule: greet  # selective import
import MyModule        # needs MyModule.greet
import MyModule: add    # selective import

Módulos estándar

Módulos de la librería estándar

julia
using Dates        # date and time
using LinearAlgebra # linear algebra
using Statistics     # statistics
using Random         # random numbers
18

Macros

Definir macros

Las macros operan sobre el AST en tiempo de compilación

julia
macro sayhi(name)
  return :(println("Hi, $name"))
end

@sayhi "Alice"  # Hi, Alice

Citación de expresiones

:() crea un objeto de expresión

julia
ex = :(1 + 2)
# :(1 + 2)

dump(ex)
# Expr
#   head: Symbol call
#   args: Array[...]

Macros comunes

Macros comunes integradas

julia
@time sleep(1)      # timing
@assert 1 == 1      # assertion
@show x              # print variable name and value
@elapsed sleep(0.1)  # return only time
@which sin(1)        # view method location
19

Metaprogramación

Construcción de expresiones

Expr construye un AST

julia
ex = Expr(:call, :+, 1, 2)
eval(ex)  # 3

# Equivalent to
eval(:(1 + 2))  # 3

Generación de código

Bucle para generar código

julia
for op in (:+, :-, :*, :/)
  eval(:(f($op, a, b) = $op(a, b)))
end

f(+, 1, 2)  # 3

Higiene de macros

La higiene de macros evita conflictos de variables

julia
macro setx(val)
  return :(x = $val)
end

# Variables in macros are hygienic and won't pollute the caller's scope
20

Computación en paralelo

Multiproceso

La macro @threads para bucles en paralelo

julia
# Start: julia --threads=4
Threads.nthreads()  # 4

Threads.@threads for i in 1:100
  results[i] = compute(i)
end

Computación distribuida

Librería estándar Distributed

julia
using Distributed
addprocs(4)  # add 4 worker processes

@everywhere function work(x)
  x ^ 2
end

pmap(work, 1:100)  # parallel map

Llamada remota

Llamada remota asíncrona

julia
using Distributed

ref = @spawnat :any sqrt(16)
fetch(ref)  # 4.0

# @spawnat executes on a specified process
21

Corrutinas

Task

Task es la corrutina de Julia

julia
t = Task(() -> begin
  println("running")
  return 42
end)

schedule(t)
wait(t)

Channel

Channel para comunicar corrutinas

julia
ch = Channel(32)

put!(ch, 1)
put!(ch, 2)
take!(ch)  # 1
take!(ch)  # 2

Productor-consumidor

Las corrutinas implementan el patrón productor-consumidor

julia
function producer(ch)
  for i in 1:5
    put!(ch, i)
  end
end

task = @task producer(Channel(10))
for val in task
  println(val)
end
22

Manejo de excepciones

try-catch

Los bloques try-catch-finally

julia
try
  risky()
catch e
  println("Error: $e")
finally
  cleanup()
end

Lanzar excepciones

throw lanza un objeto de excepción

julia
throw(ErrorException("something wrong"))
throw(DomainError(-1, "negative"))
error("generic error")

Excepciones personalizadas

Hereda del tipo Exception

julia
struct MyError <: Exception
  msg::String
end

throw(MyError("custom error"))

Aserciones

La macro @assert

julia
@assert x > 0 "x must be positive"
# Throws AssertionError when condition is false
23

Expresiones regulares

Expresiones regulares

r"" crea una regex

julia
re = r"\d+"
occursin(re, "abc123")  # true
match(re, "abc123")     # RegexMatch

Coincidencias

match devuelve el resultado de la coincidencia

julia
m = match(r"(\w+)@(\w+)", "user@host")
m.match   # "user@host"
m.captures  # ["user", "host"]
m[1]      # "user"

Buscar todas

eachmatch itera sobre todas las coincidencias

julia
for m in eachmatch(r"\d+", "a1b2c3")
  println(m.match)
end
# 1, 2, 3

Reemplazar

replace admite regex

julia
replace("a1b2c3", r"\d" => "#")
# "a#b#c#"

replace("hello", r"l" => "L" => count=1)
# "heLlo"
24

DateTime

Crear fechas

Librería estándar Dates

julia
using Dates

now()                    # current time
Date(2024, 1, 15)       # date
DateTime(2024, 1, 15, 10, 30)  # datetime

Formato

Formateo y análisis

julia
using Dates

dt = now()
Dates.format(dt, "yyyy-mm-dd HH:MM:SS")
Date("2024-01-15", "yyyy-mm-dd")

Aritmética de fechas

Tipos de intervalos de tiempo

julia
using Dates

d1 = Date(2024, 1, 1)
d2 = d1 + Day(30)     # add 30 days
diff = d2 - d1        # 30 days
Day(1) + Hour(12)     # datetime arithmetic
25

Paquetes

Instalar paquetes

Pkg.add instala paquetes

julia
using Pkg
Pkg.add("Plots")
Pkg.add(["DataFrames", "CSV"])
Pkg.rm("Plots")  # remove

Gestión de paquetes

Comandos habituales de Pkg

julia
Pkg.status()    # view installed
Pkg.update()    # update all
Pkg.instantiate()  # install per Project.toml
Pkg.activate("env")  # activate environment

Entornos

Gestión de entornos de proyecto

julia
# Project.toml defines dependencies
# Manifest.toml locks versions

Pkg.activate("myproject")  # activate environment
Pkg.resolve()  # resolve dependencies
26

Gestor Pkg

Modo Pkg del REPL

] entra en el modo Pkg del REPL

julia
julia> ]
pkg> add Plots
pkg> rm Plots
pkg> status
pkg> update
pkg> test Plots

Crear paquetes

generate crea el esqueleto de un paquete

julia
pkg> generate MyPackage

# Directory structure
# MyPackage/
#   Project.toml
#   src/MyPackage.jl

Modo desarrollo

dev instala en modo desarrollo

julia
pkg> dev ./MyPackage  # local development
pkg> dev MyPackage    # dev version from GitHub
pkg> free MyPackage   # exit development mode
27

Interoperabilidad

Llamar a C

ccall llama a funciones de C

julia
ccall((:sqrt, "libm"), Float64, (Float64,), 16.0)
# 4.0

Llamar a Python

PyCall.jl llama a Python

julia
using PyCall
np = pyimport("numpy")
np.array([1, 2, 3])
np.mean([1, 2, 3])

Llamar a R

RCall.jl llama a R

julia
using RCall
R"sd(c(1,2,3,4,5))"  # call R code
28

Computación en GPU

Arrays CUDA

CUDA.jl es compatible con GPUs NVIDIA

julia
using CUDA

a = CUDA.ones(1000)
b = CUDA.zeros(1000)
c = a .+ b  # operations on GPU

Kernels de GPU

@cuda lanza un kernel de GPU

julia
using CUDA

function kernel!(a)
  i = threadIdx().x
  if i <= length(a)
    @inbounds a[i] *= 2
  end
  return
end

@cuda threads=256 kernel!(a)

GPU AMD

AMDGPU.jl es compatible con GPUs AMD

julia
using AMDGPU

a = ROCArray(ones(100))
b = a .* 2  # operations on AMD GPU

Was this helpful?