{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introducción a Julia\n", "\n", "Vamos a dar una breve introducción al lenguaje **Julia**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Primitivas, funciones básicas y operdores\n", "\n", "El comando para mostrar un resultado en pantalla es `println()`, como se ve a continuación" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Julia!\n" ] } ], "source": [ "println(\"Hello Julia!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Los comentarios de una sola linea empiezan con #, mientras que los multilinea empiezan con #= y terminan con =#" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Este si\n" ] } ], "source": [ "println(\"Este si\")\n", "# println(\"Este no\")\n", "#=\n", "println(\"Mucho menos\")\n", "println(\"estos dos\")\n", "=#\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Existen tambien varios tipos de números, pasando por los enteros, punto flotante, complejos y racionales" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2//3" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Int64\n", "3\n", "\n", "# Float64\n", "3.2\n", "\n", "# Complex{Int64}\n", "2 + 1im\n", "\n", "# Rational{Int64}\n", "2//3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "También como tal se pueden aplicar las diferentes operaciones entre números" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 + 1 # => 2\n", "8 - 1 # => 7\n", "10 * 2 # => 20\n", "35 / 5 # => 7.0\n", "5 / 2 # => 2.5\n", "div(5, 2) # => 2\n", "5 \\ 35 # => 7.0\n", "2 ^ 2 # => 4\n", "12 % 10 # => 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "También se pueden aplicar las operaciones binarias o *bitwise*" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "~2 # => -3 # not\n", "3 & 5 # => 1 # and\n", "2 | 4 # => 6 # or\n", "2 $ 4 # => 6 # xor\n", "2 >>> 1 # => 1 # corrimeinto lógico a la derecha\n", "2 >> 1 # => 1 # corrimeinto aritmético a la derecha\n", "2 << 1 # => 4 # corrimeinto lógico/aritmético a la izquierda" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Los valores booleanos son **true** y **false**, sin mayúscula inicial, y se presentan a continuación" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "true" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "!true # => false\n", "!false # => true\n", "1 == 1 # => true\n", "2 == 1 # => false\n", "1 != 1 # => false\n", "2 != 1 # => true\n", "1 < 10 # => true\n", "1 > 10 # => false\n", "2 <= 2 # => true\n", "2 >= 2 # => true" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Otra característica es que los comparadores se pueden poner encadenados" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "false" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 < 2 < 3 # => true\n", "2 < 3 < 2 # => false" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Las cadenas van entre comilla doble, los caracteres en comilla sencilla y se puede usar la interpolación de cadenas, a continuación se muestran dos maneras de poner valores en estas" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 is less than " ] }, { "data": { "text/plain": [ "\"2 + 2 = 4\"" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "5.300000" ] } ], "source": [ "@printf \"%d is less than %f\" 4.5 5.3 # => \"5 is less than 5.300000\"\n", "\"2 + 2 = $(2 + 2)\" # => \"2 + 2 = 4\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Variables y colecciones\n", "Las variables no necesariamente deben ser tipadas, por lo que no deben instanciarse antes de asignarlas" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "some_var = 5\n", "some_var" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lo cual no significa que acceder a una variable antes de asignarla no genere un error (de paso se muestra el manejo de errores)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "UndefVarError(:some_other_var)\n" ] } ], "source": [ "try\n", " some_other_var # => ERROR: some_other_var no definida\n", "catch e\n", " println(e)\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Para las listas hay que tener en cuenta que el indice va desde **1** hasta **n**" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = Int64[] # arreglo vacio\n", "push!(a,1) # => [1]\n", "push!(a,2) # => [1,2]\n", "a[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "La instanciación puede indicar el tipo o dejarlo de manera automática" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = [4, 5, 6] # => Int64 [4, 5, 6]\n", "b = [4; 5; 6] # => Int64 [4, 5, 6]\n", "b = Int8[4, 5, 6] # => Int8 [4, 5, 6]\n", "b[1] # => 4\n", "b[end] # => 6" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "El signo de exclamación **!** al final de una función indica que esta modifica el estado de los parámetros" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3-element Array{Int64,1}:\n", " 4\n", " 5\n", " 6" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr = [5,4,6]\n", "sort(arr) # => [4,5,6]; arr es [5,4,6]\n", "sort!(arr) # => [4,5,6]; arr es [4,5,6]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Los arreglos pueden ser creados a partir de rangos, y para acceder a estos puede igual hacerse por rangos *(slice)*" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4-element Array{Int64,1}:\n", " 2\n", " 3\n", " 4\n", " 5" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1:5;] # => Int64 [1,2,3,4,5]\n", "a[1:3] # => [1, 2, 3]\n", "a[2:end] # => [2, 3, 4, 5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Los métodos más comunes para listas son:\n", "\n", " - __push!(arr, elm)__: agrega el elemento _elm_ al final del arreglo _arr_\n", " - __pop!(arr)__: elimina y retorna el elemento final del arreglo _arr_\n", " - __shift!(arr)__: elimina y retorna el primer elemento del arreglo _arr_\n", " - __unshift!(arr, elm)__: agrega el elemento _elm_ al principio del arreglo _arr_\n", " - __sort!(arr)__: ordena de forma ascendente el arreglo _arr_\n", " - __splice!(arr, pos)__: elimina y retorna el elemento del arreglo _arr_ en la posición _pos_\n", " - __append!(arr1, arr2)__: concatena los arreglos _arr1_ y _arr2_\n", " - __in(elm, arr)__: revisa si el elemento _elm_ pertence al arreglo _arr_\n", " - __lenght(arr)__: devuelve la cantidad de elementos en el arreglo _arr_\n", "\n", "Las **tuplas** se comportan de manera similar a las listas, con la excepción de que son inmutables." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(1,2,3)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tupla = (1, 2, 3)\n", "otra_tupla = 1, 2, 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Para el uso de diccionarios, su instanciación puede ser vacía o con objetos" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Dict{ASCIIString,Int64} with 3 entries:\n", " \"two\" => 2\n", " \"one\" => 1\n", " \"three\" => 3" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "empty_dict = Dict() # instanciación vacía\n", "filled_dict = Dict(\"one\"=> 1, \"two\"=> 2, \"three\"=> 3) # instanciación con elementos" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Para acceder a las llaves y valores como listas de un diccionario" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Base.ValueIterator for a Dict{ASCIIString,Int64} with 3 entries. Values:\n", " 2\n", " 1\n", " 3" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "keys(filled_dict)\n", "values(filled_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Se puede saber si una llave o una llave-valor hacen parte del diccionario" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "false" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "in((\"one\" => 1), filled_dict) # => true\n", "in((\"two\" => 3), filled_dict) # => false\n", "haskey(filled_dict, \"one\") # => true\n", "haskey(filled_dict, 1) # => false" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Se pueden hacer listas desordenadas sin elementos repetidos de la siguiente forma" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Set([4,2,3,1])" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "empty_set = Set() # => Set{Any}()\n", "filled_set = Set([1,2,2,3,4]) # => Set{Int64}(1,2,3,4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sobre estos elementos se pueden hacer operaciones de conjuntos como los que se muestran a continuación" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Set([4,1])" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "other_set = Set([3, 4, 5, 6]) # => Set{Int64}(6,4,5,3)\n", "intersect(filled_set, other_set) # => Set{Int64}(3,4,5)\n", "union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6)\n", "setdiff(Set([1,2,3,4]),Set([2,3,5])) # => Set{Int64}(1,4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Control de flujo\n", "\n", "Para las estructuras __if-else__ no afecta la identación, y se muestra de la siguiente forma" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "some_var is smaller than 10.\n" ] } ], "source": [ "some_var = 5\n", "\n", "if some_var > 10\n", " println(\"some_var is totally bigger than 10.\")\n", "elseif some_var < 10\n", " println(\"some_var is smaller than 10.\")\n", "else\n", " println(\"some_var is indeed 10.\")\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "El ciclo __for__ actua sobre iterables (_Range_, _Array_, _Set_, _Dict_ y _AbstractString_)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dog is a mammal\n", "cat is a mammal\n", "mouse is a mammal\n" ] } ], "source": [ "for animal=[\"dog\", \"cat\", \"mouse\"]\n", " println(\"$animal is a mammal\")\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "En los diccionarios se puede iterar sobre la llave-valor (se puede usar indiferentemente el __=__ o el __in__)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mouse is a mammal\n", "cat is a mammal\n", "dog is a mammal\n" ] } ], "source": [ "for (k,v) in Dict(\"dog\"=>\"mammal\",\"cat\"=>\"mammal\",\"mouse\"=>\"mammal\")\n", " println(\"$k is a $v\")\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "El ciclo __while__ se realiza de la siguiente manera" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n" ] } ], "source": [ "x = 0\n", "while x < 4\n", " println(x)\n", " x += 1\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Funciones\n", "\n", "Las funciones retornan la última sentencia" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x is 1 and y is 3\n" ] }, { "data": { "text/plain": [ "4" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "function add(x, y)\n", " println(\"x is $x and y is $y\")\n", " x + y\n", "end\n", "\n", "add(1,3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Se pueden hacer funciones como asignaciones también" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f_add(x, y) = x + y # => \"f (generic function with 1 method)\"\n", "f_add(3, 4) # => 7" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Para devolver varios valores se pueden usar tuplas" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(7,-1)" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(x, y) = x + y, x - y\n", "f(3, 4) # => (7, -1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Para tener una cantidad indefinida de valores se puede usar el operador _splat_" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1,2)\n", "(1,2,3,4)\n" ] } ], "source": [ "function varargs(args...)\n", " println(args)\n", "end\n", "\n", "varargs(1,2)\n", "varargs(1,2,3,4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Este operador también se puede usar para \"distribuir\" los argumentos" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x is 5 and y is 6\n" ] }, { "data": { "text/plain": [ "11" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "x is 5 and y is 6\n" ] } ], "source": [ "add([5,6]...) # esto es equivalente a add(5,6)\n", "x = (5,6) # => (5,6)\n", "add(x...) # esto es equivalente a add(5,6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Para los valores por defecto como argumentos como para la elección del parámetro" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Dict{ASCIIString,Any} with 2 entries:\n", " \"name2\" => \"ness\"\n", " \"k1\" => 4" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "function defaults(a,b,x=5,y=6)\n", " return \"$a $b and $x $y\"\n", "end\n", "defaults(1,2)\n", "defaults(1,2,3)\n", "\n", "\n", "function keyword_args(;k1=4,name2=\"hello\") # importante el ;\n", " return Dict(\"k1\"=>k1,\"name2\"=>name2)\n", "end\n", "keyword_args(name2=\"ness\") # => [\"name2\"=>\"ness\",\"k1\"=>4]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Julia 0.4.5", "language": "julia", "name": "julia-0.4" }, "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "0.4.5" } }, "nbformat": 4, "nbformat_minor": 0 }