mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-04-27 07:33:57 +00:00
[hy/*] proofread/update
This commit is contained in:
parent
8fb3356473
commit
cbb2eb4f00
@ -10,15 +10,13 @@ lang: es-es
|
|||||||
|
|
||||||
Hy es un lenguaje de Lisp escrito sobre Python. Esto es posible convirtiendo
|
Hy es un lenguaje de Lisp escrito sobre Python. Esto es posible convirtiendo
|
||||||
código Hy en un árbol abstracto de Python (ast). Por lo que, esto permite a
|
código Hy en un árbol abstracto de Python (ast). Por lo que, esto permite a
|
||||||
Hy llamar a código Pyhton nativo y viceversa.
|
Hy llamar a código Python nativo y viceversa.
|
||||||
|
|
||||||
Este tutorial funciona para hy >= 0.9.12
|
```hylang
|
||||||
|
|
||||||
```clojure
|
|
||||||
;; Esto es una intrucción muy básica a Hy, como la del siguiente enlace
|
;; Esto es una intrucción muy básica a Hy, como la del siguiente enlace
|
||||||
;; http://try-hy.appspot.com
|
;; https://hylang.org/try-hy
|
||||||
;;
|
;;
|
||||||
; Comentarios usando punto y coma, como en otros LISPS
|
; Comentarios usando punto y coma, como en otros Lisps
|
||||||
|
|
||||||
;; Nociones básicas de expresiones
|
;; Nociones básicas de expresiones
|
||||||
; Los programas List están hechos de expresiones simbólicas como la siguiente
|
; Los programas List están hechos de expresiones simbólicas como la siguiente
|
||||||
@ -28,7 +26,7 @@ Este tutorial funciona para hy >= 0.9.12
|
|||||||
|
|
||||||
;; Tipos de datos simples
|
;; Tipos de datos simples
|
||||||
; Todos los tipos de datos simples son exactamente semejantes a sus homólogos
|
; Todos los tipos de datos simples son exactamente semejantes a sus homólogos
|
||||||
; en python
|
; en Python
|
||||||
42 ; => 42
|
42 ; => 42
|
||||||
3.14 ; => 3.14
|
3.14 ; => 3.14
|
||||||
True ; => True
|
True ; => True
|
||||||
@ -36,13 +34,13 @@ True ; => True
|
|||||||
|
|
||||||
; Vamos a comenzar con un poco de arimética simple
|
; Vamos a comenzar con un poco de arimética simple
|
||||||
(+ 4 1) ;=> 5
|
(+ 4 1) ;=> 5
|
||||||
; el operador es aplicado a todos los argumentos, como en otros lisps
|
; el operador es aplicado a todos los argumentos, como en otros Lisps
|
||||||
(+ 4 1 2 3) ;=> 10
|
(+ 4 1 2 3) ;=> 10
|
||||||
(- 2 1) ;=> 1
|
(- 2 1) ;=> 1
|
||||||
(* 4 2) ;=> 8
|
(* 4 2) ;=> 8
|
||||||
(/ 4 1) ;=> 4
|
(/ 4 1) ;=> 4
|
||||||
(% 4 2) ;=> 0 o operador módulo
|
(% 4 2) ;=> 0 o operador módulo
|
||||||
; la exponenciación es representada por el operador ** como python
|
; la exponenciación es representada por el operador ** como Python
|
||||||
(** 3 2) ;=> 9
|
(** 3 2) ;=> 9
|
||||||
; las funciones anidadas funcionan como lo esperado
|
; las funciones anidadas funcionan como lo esperado
|
||||||
(+ 2 (* 4 2)) ;=> 10
|
(+ 2 (* 4 2)) ;=> 10
|
||||||
@ -58,9 +56,9 @@ True ; => True
|
|||||||
(def *foo* 42)
|
(def *foo* 42)
|
||||||
;; otros tipos de datos de almacenamiento
|
;; otros tipos de datos de almacenamiento
|
||||||
; strings, lists, tuples & dicts
|
; strings, lists, tuples & dicts
|
||||||
; estos son exactamente los mismos tipos de almacenamiento en python
|
; estos son exactamente los mismos tipos de almacenamiento en Python
|
||||||
"hello world" ;=> "hello world"
|
"hello world" ;=> "hello world"
|
||||||
; las operaciones de cadena funcionan de manera similar en python
|
; las operaciones de cadena funcionan de manera similar en Python
|
||||||
(+ "hello " "world") ;=> "hello world"
|
(+ "hello " "world") ;=> "hello world"
|
||||||
; Las listas se crean usando [], la indexación comienza en 0
|
; Las listas se crean usando [], la indexación comienza en 0
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
@ -96,31 +94,31 @@ True ; => True
|
|||||||
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
||||||
|
|
||||||
;; operaciones de secuencia
|
;; operaciones de secuencia
|
||||||
; hy tiene algunas utilidades incluidas para operaciones de secuencia, etc.
|
; Hy tiene algunas utilidades incluidas para operaciones de secuencia, etc.
|
||||||
; recuperar el primer elemento usando 'first' o 'car'
|
; recuperar el primer elemento usando 'first' o 'car'
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
(setv mydict {"a" 1 "b" 2})
|
(setv mydict {"a" 1 "b" 2})
|
||||||
(first mylist) ;=> 1
|
(first mylist) ;=> 1
|
||||||
|
|
||||||
; corte listas usando 'slice'
|
; corte listas usando 'cut'
|
||||||
(slice mylist 1 3) ;=> [2 3]
|
(cut mylist 1 3) ;=> [2 3]
|
||||||
|
|
||||||
; obtener elementos de una lista o dict usando 'get'
|
; obtener elementos de una lista o dict usando 'get'
|
||||||
(get mylist 1) ;=> 2
|
(get mylist 1) ;=> 2
|
||||||
(get mydict "b") ;=> 2
|
(get mydict "b") ;=> 2
|
||||||
; la lista de indexación comienza a partir de 0, igual que en python
|
; la lista de indexación comienza a partir de 0, igual que en Python
|
||||||
; assoc puede definir elementos clave/índice
|
; assoc puede definir elementos clave/índice
|
||||||
(assoc mylist 2 10) ; crear mylist [1 2 10 4]
|
(assoc mylist 2 10) ; crear mylist [1 2 10 4]
|
||||||
(assoc mydict "c" 3) ; crear mydict {"a" 1 "b" 2 "c" 3}
|
(assoc mydict "c" 3) ; crear mydict {"a" 1 "b" 2 "c" 3}
|
||||||
; hay muchas otras funciones que hacen que trabajar con secuencias sea
|
; hay muchas otras funciones que hacen que trabajar con secuencias sea
|
||||||
; entretenido
|
; entretenido
|
||||||
|
|
||||||
;; Python interop
|
;; Python interop
|
||||||
;; los import funcionan exactamente como en python
|
;; los import funcionan exactamente como en Python
|
||||||
(import datetime)
|
(import datetime)
|
||||||
(import [functools [partial reduce]]) ; importa fun1 e fun2 del module1
|
(import functools [partial reduce]) ; importa fun1 e fun2 del module1
|
||||||
(import [matplotlib.pyplot :as plt]) ; haciendo una importación en foo como en bar
|
(import matplotlib.pyplot :as plt) ; haciendo una importación en foo como en bar
|
||||||
; todos los métodos de python incluídos etc. son accesibles desde hy
|
; todos los métodos de Python incluídos etc. son accesibles desde Hy
|
||||||
; a.foo(arg) is called as (.foo a arg)
|
; a.foo(arg) is called as (.foo a arg)
|
||||||
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
||||||
|
|
||||||
@ -132,12 +130,9 @@ True ; => True
|
|||||||
|
|
||||||
; anidar múltiples cláusulas 'if else if' con condiciones
|
; anidar múltiples cláusulas 'if else if' con condiciones
|
||||||
(cond
|
(cond
|
||||||
[(= someval 42)
|
(= someval 42) (print "Life, universe and everything else!")
|
||||||
(print "Life, universe and everything else!")]
|
(> someval 42) (print "val too large")
|
||||||
[(> someval 42)
|
(< someval 42) (print "val too small"))
|
||||||
(print "val too large")]
|
|
||||||
[(< someval 42)
|
|
||||||
(print "val too small")])
|
|
||||||
|
|
||||||
; declaraciones de grupo con 'do', son ejecutadas secuencialmente
|
; declaraciones de grupo con 'do', son ejecutadas secuencialmente
|
||||||
; formas como defn tienen un 'do' implícito
|
; formas como defn tienen un 'do' implícito
|
||||||
@ -155,22 +150,20 @@ True ; => True
|
|||||||
|
|
||||||
;; clases
|
;; clases
|
||||||
; las clases son definidas de la siguiente manera
|
; las clases son definidas de la siguiente manera
|
||||||
(defclass Wizard [object]
|
(defclass Wizard [object]
|
||||||
[[--init-- (fn [self spell]
|
(defn __init__ [self spell]
|
||||||
(setv self.spell spell) ; init the attr magic
|
(setv self.spell spell))
|
||||||
None)]
|
|
||||||
[get-spell (fn [self]
|
|
||||||
self.spell)]])
|
|
||||||
|
|
||||||
;; acesse hylang.org
|
(defn get-spell [self]
|
||||||
|
self.spell))
|
||||||
```
|
```
|
||||||
|
|
||||||
### Otras lecturas
|
### Otras lecturas
|
||||||
|
|
||||||
Este tutorial apenas es una introducción básica para hy/lisp/python.
|
Este tutorial apenas es una introducción básica para Hy/Lisp/Python.
|
||||||
|
|
||||||
Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org)
|
Docs Hy: [https://hylang.org/hy/doc](https://hylang.org/hy/doc)
|
||||||
|
|
||||||
Repo Hy en GitHub: [http://github.com/hylang/hy](http://github.com/hylang/hy)
|
Repo Hy en GitHub: [https://github.com/hylang/hy](https://github.com/hylang/hy)
|
||||||
|
|
||||||
Acceso a freenode irc con #hy, hashtag en twitter: #hylang
|
Acceso a freenode irc con #hy, hashtag en twitter: #hylang
|
||||||
|
@ -8,14 +8,12 @@ translators:
|
|||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
---
|
---
|
||||||
|
|
||||||
Hy est un dialecte du lisp bâti par dessus python. Il fonctionne en
|
Hy est un dialecte du Lisp bâti par dessus Python. Il fonctionne en
|
||||||
convertissant le code hy en un arbre de syntaxe abstraite de python (ast).
|
convertissant le code Hy en un arbre de syntaxe abstraite de Python (ast).
|
||||||
Ceci permet à hy d'appeler du code python et à python d'appeler du code hy.
|
Ceci permet à Hy d'appeler du code Python et à Python d'appeler du code Hy.
|
||||||
|
|
||||||
Ce tutoriel fonctionne pour hy > 0.9.12
|
```hylang
|
||||||
|
;; Ceci est une introduction simple à Hy, pour un tutoriel rapide aller à
|
||||||
```clojure
|
|
||||||
;; Ceci est une introduction simple à hy, pour un tutoriel rapide aller à
|
|
||||||
;; http://try-hy.appspot.com
|
;; http://try-hy.appspot.com
|
||||||
;;
|
;;
|
||||||
; Les commentaires se font avec des points-virgules, comme les autres LISPS
|
; Les commentaires se font avec des points-virgules, comme les autres LISPS
|
||||||
@ -29,7 +27,7 @@ Ce tutoriel fonctionne pour hy > 0.9.12
|
|||||||
|
|
||||||
;; les types de données simples
|
;; les types de données simples
|
||||||
; Tous les types de données simples sont exactement similaires à leurs
|
; Tous les types de données simples sont exactement similaires à leurs
|
||||||
; homologues de python
|
; homologues de Python
|
||||||
42 ; => 42
|
42 ; => 42
|
||||||
3.14 ; => 3.14
|
3.14 ; => 3.14
|
||||||
True ; => True
|
True ; => True
|
||||||
@ -43,7 +41,7 @@ True ; => True
|
|||||||
(* 4 2) ;=> 8
|
(* 4 2) ;=> 8
|
||||||
(/ 4 1) ;=> 4
|
(/ 4 1) ;=> 4
|
||||||
(% 4 2) ;=> 0 l'opérateur modulo
|
(% 4 2) ;=> 0 l'opérateur modulo
|
||||||
; l'opérateur d'élévation à la puissance est représenté par ** comme en python
|
; l'opérateur d'élévation à la puissance est représenté par ** comme en Python
|
||||||
(** 3 2) ;=> 9
|
(** 3 2) ;=> 9
|
||||||
; les expressions imbriquées vont se comporter comme on s'y attend
|
; les expressions imbriquées vont se comporter comme on s'y attend
|
||||||
(+ 2 (* 4 2)) ;=> 10
|
(+ 2 (* 4 2)) ;=> 10
|
||||||
@ -60,9 +58,9 @@ True ; => True
|
|||||||
(def *foo* 42)
|
(def *foo* 42)
|
||||||
;; d'autres types de conteneurs
|
;; d'autres types de conteneurs
|
||||||
; les chaînes, les listes, les tuples et dicts
|
; les chaînes, les listes, les tuples et dicts
|
||||||
; ce sont exactement les mêmes que les types de conteneurs de python
|
; ce sont exactement les mêmes que les types de conteneurs de Python
|
||||||
"hello world" ;=> "hello world"
|
"hello world" ;=> "hello world"
|
||||||
; les opérations sur les chaînes fonctionnent comme en python
|
; les opérations sur les chaînes fonctionnent comme en Python
|
||||||
(+ "hello " "world") ;=> "hello world"
|
(+ "hello " "world") ;=> "hello world"
|
||||||
; les listes sont créés en utilisant [], l'indexation commence à 0
|
; les listes sont créés en utilisant [], l'indexation commence à 0
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
@ -70,7 +68,7 @@ True ; => True
|
|||||||
(setv mytuple (, 1 2))
|
(setv mytuple (, 1 2))
|
||||||
; les dictionnaires sont des paires clé-valeur
|
; les dictionnaires sont des paires clé-valeur
|
||||||
(setv dict1 {"key1" 42 "key2" 21})
|
(setv dict1 {"key1" 42 "key2" 21})
|
||||||
; :nom peut être utilisé pour définir des mots clés dans hy qui peuvent être
|
; :nom peut être utilisé pour définir des mots clés dans Hy qui peuvent être
|
||||||
; utilisées comme clés
|
; utilisées comme clés
|
||||||
(setv dict2 {:key1 41 :key2 20})
|
(setv dict2 {:key1 41 :key2 20})
|
||||||
; utilisez `get' pour obtenir l'élément à l'index / clé
|
; utilisez `get' pour obtenir l'élément à l'index / clé
|
||||||
@ -101,30 +99,30 @@ True ; => True
|
|||||||
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
||||||
|
|
||||||
;; Opérations sur les séquences
|
;; Opérations sur les séquences
|
||||||
; hy a des utilitaires natifs pour les opérations sur les séquences etc.
|
; Hy a des utilitaires natifs pour les opérations sur les séquences etc.
|
||||||
; récupérez le premier élément en utilisant `first' ou `car'
|
; récupérez le premier élément en utilisant `first' ou `car'
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
(setv mydict {"a" 1 "b" 2})
|
(setv mydict {"a" 1 "b" 2})
|
||||||
(first mylist) ;=> 1
|
(first mylist) ;=> 1
|
||||||
|
|
||||||
; découpez les listes en utilisant slice
|
; découpez les listes en utilisant cut
|
||||||
(slice mylist 1 3) ;=> [2 3]
|
(cut mylist 1 3) ;=> [2 3]
|
||||||
|
|
||||||
; obtenez les éléments d'une liste ou dict en utilisant `get'
|
; obtenez les éléments d'une liste ou dict en utilisant `get'
|
||||||
(get mylist 1) ;=> 2
|
(get mylist 1) ;=> 2
|
||||||
(get mydict "b") ;=> 2
|
(get mydict "b") ;=> 2
|
||||||
; l'indexation des listes commence à 0 comme en python
|
; l'indexation des listes commence à 0 comme en Python
|
||||||
; assoc peut définir les éléments à clés/index
|
; assoc peut définir les éléments à clés/index
|
||||||
(assoc mylist 2 10) ; makes mylist [1 2 10 4]
|
(assoc mylist 2 10) ; makes mylist [1 2 10 4]
|
||||||
(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
|
(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
|
||||||
; il ya tout un tas d'autres fonctions de base qui rend le travail avec
|
; il ya tout un tas d'autres fonctions de base qui rend le travail avec
|
||||||
; les séquences amusant
|
; les séquences amusant
|
||||||
|
|
||||||
;; les importations fonctionnent comme en pyhtonn
|
;; les importations fonctionnent comme en Python
|
||||||
(import datetime)
|
(import datetime)
|
||||||
(import [functools [partial reduce]]) ; importe fun1 et fun2 de module1
|
(import functools [partial reduce]) ; importe fun1 et fun2 de module1
|
||||||
(import [matplotlib.pyplot :as plt]) ; faire une importation foo comme bar
|
(import matplotlib.pyplot :as plt) ; faire une importation foo comme bar
|
||||||
; toutes les méthodes natives de python sont accessibles à partir de hy
|
; toutes les méthodes natives de Python sont accessibles à partir de Hy
|
||||||
; a.foo(arg) est appelé (.foo a arg)
|
; a.foo(arg) est appelé (.foo a arg)
|
||||||
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
||||||
|
|
||||||
@ -136,12 +134,9 @@ True ; => True
|
|||||||
|
|
||||||
; imbriquez plusieurs if else if avec le mot clé cond
|
; imbriquez plusieurs if else if avec le mot clé cond
|
||||||
(cond
|
(cond
|
||||||
[(= someval 42)
|
(= someval 42) (print "Life, universe and everything else!")
|
||||||
(print "Life, universe and everything else!")]
|
(> someval 42) (print "val too large")
|
||||||
[(> someval 42)
|
(< someval 42) (print "val too small"))
|
||||||
(print "val too large")]
|
|
||||||
[(< someval 42)
|
|
||||||
(print "val too small")])
|
|
||||||
|
|
||||||
; groupez les expressions avec do, ceux-ci seront executé séquentiellemnt
|
; groupez les expressions avec do, ceux-ci seront executé séquentiellemnt
|
||||||
; les expressions comme defn ont un do implicite
|
; les expressions comme defn ont un do implicite
|
||||||
@ -155,26 +150,24 @@ True ; => True
|
|||||||
"sherlock" "moriarty"
|
"sherlock" "moriarty"
|
||||||
"seinfeld" "newman"}]]
|
"seinfeld" "newman"}]]
|
||||||
(for [(, h v) (.items nemesis)]
|
(for [(, h v) (.items nemesis)]
|
||||||
(print (.format "{0}'s nemesis was {1}" h v))))
|
(print (.format "{0}'s nemesis was {1}" h v))))
|
||||||
|
|
||||||
;; classes
|
;; classes
|
||||||
; les classes sont définies comme ceci
|
; les classes sont définies comme ceci
|
||||||
(defclass Wizard [object]
|
(defclass Wizard [object]
|
||||||
[[--init-- (fn [self spell]
|
(defn __init__ [self spell]
|
||||||
(setv self.spell spell) ; init the spell attr
|
(setv self.spell spell))
|
||||||
None)]
|
|
||||||
[get-spell (fn [self]
|
|
||||||
self.spell)]])
|
|
||||||
|
|
||||||
;; allez voir hylang.org
|
(defn get-spell [self]
|
||||||
|
self.spell))
|
||||||
```
|
```
|
||||||
|
|
||||||
### Lectures complémentaires
|
### Lectures complémentaires
|
||||||
|
|
||||||
Ce tutoriel est juste une simple introduction à hy/lisp/python.
|
Ce tutoriel est juste une simple introduction à Hy/Lisp/Python.
|
||||||
|
|
||||||
La documentation de HY: [http://hy.readthedocs.org](http://hy.readthedocs.org)
|
La documentation de Hy: [https://hylang.org/hy/doc](https://hylang.org/hy/doc)
|
||||||
|
|
||||||
Le repo GitHub de HY: [http://github.com/hylang/hy](http://github.com/hylang/hy)
|
Le repo GitHub de Hy: [https://github.com/hylang/hy](https://github.com/hylang/hy)
|
||||||
|
|
||||||
Sur freenode irc #hy, twitter hashtag #hylang
|
Sur freenode irc #hy, twitter hashtag #hylang
|
||||||
|
@ -6,59 +6,54 @@ contributors:
|
|||||||
- ["Zirak", "http://zirak.me"]
|
- ["Zirak", "http://zirak.me"]
|
||||||
---
|
---
|
||||||
|
|
||||||
Hy is a lisp dialect built on top of python. This is achieved by
|
Hy is a Lisp dialect built on top of Python. This is achieved by
|
||||||
converting hy code to python's abstract syntax tree (ast). This allows
|
converting Hy code to Python's abstract syntax tree (AST). This allows
|
||||||
hy to call native python code or python to call native hy code as well
|
Hy to call native Python code or Python to call native Hy code as well
|
||||||
|
|
||||||
This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11.
|
```hylang
|
||||||
|
; Semicolon comments, like other Lisps
|
||||||
|
|
||||||
```clojure
|
;; S-expression basics
|
||||||
;; this gives an gentle introduction to hy
|
; Lisp programs are made of symbolic expressions or sexps which
|
||||||
;;
|
|
||||||
; Semicolon comments, like other LISPS
|
|
||||||
|
|
||||||
;; s-expression basics
|
|
||||||
; lisp programs are made of symbolic expressions or sexps which
|
|
||||||
; resemble
|
; resemble
|
||||||
(some-function args)
|
(some-function args)
|
||||||
; now the quintessential hello world
|
; now the quintessential hello world
|
||||||
(print "hello world")
|
(print "hello world")
|
||||||
|
|
||||||
;; simple data types
|
;; Simple data types
|
||||||
; All simple data types are exactly similar to their python counterparts
|
; All simple data types are the same as their Python counterparts
|
||||||
; which
|
|
||||||
42 ; => 42
|
42 ; => 42
|
||||||
3.14 ; => 3.14
|
3.14 ; => 3.14
|
||||||
True ; => True
|
True ; => True
|
||||||
4+10j ; => (4+10j) a complex number
|
4+10j ; => (4+10j) a complex number
|
||||||
|
|
||||||
; lets start with some really simple arithmetic
|
; lets start with some simple arithmetic
|
||||||
(+ 4 1) ;=> 5
|
(+ 4 1) ;=> 5
|
||||||
; the operator is applied to all arguments, like other lisps
|
; the operator is applied to all arguments, like other Lisps
|
||||||
(+ 4 1 2 3) ;=> 10
|
(+ 4 1 2 3) ;=> 10
|
||||||
(- 2 1) ;=> 1
|
(- 2 1) ;=> 1
|
||||||
(* 4 2) ;=> 8
|
(* 4 2) ;=> 8
|
||||||
(/ 4 1) ;=> 4
|
(/ 4 1) ;=> 4
|
||||||
(% 4 2) ;=> 0 the modulo operator
|
(% 4 2) ;=> 0 the modulo operator
|
||||||
; power is represented by ** operator like python
|
; power is represented by the ** operator, like Python
|
||||||
(** 3 2) ;=> 9
|
(** 3 2) ;=> 9
|
||||||
; nesting forms will do the expected thing
|
; nesting forms will do the expected thing
|
||||||
(+ 2 (* 4 2)) ;=> 10
|
(+ 2 (* 4 2)) ;=> 10
|
||||||
; also logical operators and or not and equal to etc. do as expected
|
; also logical operators and or not and equal to etc. work as expected
|
||||||
(= 5 4) ;=> False
|
(= 5 4) ;=> False
|
||||||
(not (= 5 4)) ;=> True
|
(not (= 5 4)) ;=> True
|
||||||
|
|
||||||
;; variables
|
;; Variables
|
||||||
; variables are set using setv, variable names can use utf-8 except
|
; variables are set using setv, variable names can use utf-8 except
|
||||||
; for ()[]{}",'`;#|
|
; for ()[]{}",'`;#|
|
||||||
(setv a 42)
|
(setv a 42)
|
||||||
(setv π 3.14159)
|
(setv π 3.14159)
|
||||||
(def *foo* 42)
|
(def *foo* 42)
|
||||||
;; other container data types
|
;; Other container data types
|
||||||
; strings, lists, tuples & dicts
|
; strings, lists, tuples & dicts
|
||||||
; these are exactly same as python's container types
|
; these are exactly same as Python's container types
|
||||||
"hello world" ;=> "hello world"
|
"hello world" ;=> "hello world"
|
||||||
; string operations work similar to python
|
; string operations work similar to Python
|
||||||
(+ "hello " "world") ;=> "hello world"
|
(+ "hello " "world") ;=> "hello world"
|
||||||
; lists are created using [], indexing starts at 0
|
; lists are created using [], indexing starts at 0
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
@ -66,15 +61,15 @@ True ; => True
|
|||||||
(setv mytuple (, 1 2))
|
(setv mytuple (, 1 2))
|
||||||
; dictionaries are key value pairs
|
; dictionaries are key value pairs
|
||||||
(setv dict1 {"key1" 42 "key2" 21})
|
(setv dict1 {"key1" 42 "key2" 21})
|
||||||
; :name can be used to define keywords in hy which can be used for keys
|
; :name can be used to define keywords in Hy which can be used for keys
|
||||||
(setv dict2 {:key1 41 :key2 20})
|
(setv dict2 {:key1 41 :key2 20})
|
||||||
; use `get' to get the element at an index/key
|
; use `get' to get the element at an index/key
|
||||||
(get mylist 1) ;=> 2
|
(get mylist 1) ;=> 2
|
||||||
(get dict1 "key1") ;=> 42
|
(get dict1 "key1") ;=> 42
|
||||||
; Alternatively if keywords were used they can directly be called
|
; Alternatively if keywords were used they can be called directly
|
||||||
(:key1 dict2) ;=> 41
|
(:key1 dict2) ;=> 41
|
||||||
|
|
||||||
;; functions and other program constructs
|
;; Functions and other program constructs
|
||||||
; functions are defined using defn, the last sexp is returned by default
|
; functions are defined using defn, the last sexp is returned by default
|
||||||
(defn greet [name]
|
(defn greet [name]
|
||||||
"A simple greeting" ; an optional docstring
|
"A simple greeting" ; an optional docstring
|
||||||
@ -105,21 +100,19 @@ True ; => True
|
|||||||
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
||||||
|
|
||||||
;; Sequence operations
|
;; Sequence operations
|
||||||
; hy has some builtin utils for sequence operations etc.
|
; Hy has some builtin utils for sequence operations etc.
|
||||||
; retrieve the first element using `first' or `car'
|
; retrieve the first element using `first' or `car'
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
(setv mydict {"a" 1 "b" 2})
|
(setv mydict {"a" 1 "b" 2})
|
||||||
(first mylist) ;=> 1
|
(first mylist) ;=> 1
|
||||||
|
|
||||||
; slice lists using slice
|
; slice lists using cut
|
||||||
(slice mylist 1 3) ;=> [2 3]
|
|
||||||
; or, in hy 0.11, use cut instead:
|
|
||||||
(cut mylist 1 3) ;=> [2 3]
|
(cut mylist 1 3) ;=> [2 3]
|
||||||
|
|
||||||
; get elements from a list or dict using `get'
|
; get elements from a list or dict using `get'
|
||||||
(get mylist 1) ;=> 2
|
(get mylist 1) ;=> 2
|
||||||
(get mydict "b") ;=> 2
|
(get mydict "b") ;=> 2
|
||||||
; list indexing starts from 0 same as python
|
; list indexing starts from 0, same as Python
|
||||||
; assoc can set elements at keys/indexes
|
; assoc can set elements at keys/indexes
|
||||||
(assoc mylist 2 10) ; makes mylist [1 2 10 4]
|
(assoc mylist 2 10) ; makes mylist [1 2 10 4]
|
||||||
(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
|
(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
|
||||||
@ -127,11 +120,11 @@ True ; => True
|
|||||||
; sequences fun
|
; sequences fun
|
||||||
|
|
||||||
;; Python interop
|
;; Python interop
|
||||||
;; import works just like in python
|
;; import works just like in Python
|
||||||
(import datetime)
|
(import datetime)
|
||||||
(import [functools [partial reduce]]) ; imports fun1 and fun2 from module1
|
(import functools [partial reduce]) ; imports partial and reduce from functools
|
||||||
(import [matplotlib.pyplot :as plt]) ; doing an import foo as bar
|
(import matplotlib.pyplot :as plt) ; imports foo as bar
|
||||||
; all builtin python methods etc. are accessible from hy
|
; all builtin Python methods etc. are accessible from Hy
|
||||||
; a.foo(arg) is called as (.foo a arg)
|
; a.foo(arg) is called as (.foo a arg)
|
||||||
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
||||||
|
|
||||||
@ -166,8 +159,8 @@ True ; => True
|
|||||||
; group statements with do, these are executed sequentially
|
; group statements with do, these are executed sequentially
|
||||||
; forms like defn have an implicit do
|
; forms like defn have an implicit do
|
||||||
(do
|
(do
|
||||||
(setv someval 10)
|
(setv someval 10)
|
||||||
(print "someval is set to " someval)) ;=> 10
|
(print "someval is set to " someval)) ;=> 10
|
||||||
|
|
||||||
; create lexical bindings with `let', all variables defined thusly
|
; create lexical bindings with `let', all variables defined thusly
|
||||||
; have local scope
|
; have local scope
|
||||||
@ -175,34 +168,24 @@ True ; => True
|
|||||||
"sherlock" "moriarty"
|
"sherlock" "moriarty"
|
||||||
"seinfeld" "newman"}]
|
"seinfeld" "newman"}]
|
||||||
(for [[h v] (.items nemesis)]
|
(for [[h v] (.items nemesis)]
|
||||||
(print (.format "{0}'s nemesis was {1}" h v))))
|
(print (.format "{0}'s nemesis was {1}" h v))))
|
||||||
|
|
||||||
;; classes
|
;; Classes
|
||||||
; classes are defined in the following way
|
; classes are defined in the following way
|
||||||
(defclass Wizard [object]
|
(defclass Wizard [object]
|
||||||
[[--init-- (fn [self spell]
|
(defn __init__ [self spell]
|
||||||
(setv self.spell spell) ; init the spell attr
|
|
||||||
None)]
|
|
||||||
[get-spell (fn [self]
|
|
||||||
self.spell)]])
|
|
||||||
|
|
||||||
; or, in hy 0.11:
|
|
||||||
(defclass Wizard [object]
|
|
||||||
(defn --init-- [self spell]
|
|
||||||
(setv self.spell spell))
|
(setv self.spell spell))
|
||||||
|
|
||||||
(defn get-spell [self]
|
(defn get-spell [self]
|
||||||
self.spell))
|
self.spell))
|
||||||
|
|
||||||
;; do checkout hylang.org
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Further Reading
|
### Further Reading
|
||||||
|
|
||||||
This tutorial is just a very basic introduction to hy/lisp/python.
|
This tutorial is just a basic introduction to Hy/Lisp/Python.
|
||||||
|
|
||||||
Hy docs are here: [http://hy.readthedocs.org](http://hy.readthedocs.org)
|
Hy docs are here: [https://hylang.org/hy/doc](https://hylang.org/hy/doc)
|
||||||
|
|
||||||
Hy's GitHub repo: [http://github.com/hylang/hy](http://github.com/hylang/hy)
|
Hy's GitHub repo: [https://github.com/hylang/hy](https://github.com/hylang/hy)
|
||||||
|
|
||||||
On freenode irc #hy, twitter hashtag #hylang
|
On freenode IRC `#hy`, twitter hashtag #hylang
|
||||||
|
@ -9,16 +9,14 @@ lang: pt-br
|
|||||||
---
|
---
|
||||||
|
|
||||||
Hy é um dialeto de Lisp escrito sobre Python. Isto é possível convertendo
|
Hy é um dialeto de Lisp escrito sobre Python. Isto é possível convertendo
|
||||||
código Hy em árvore sintática abstrata python (ast). Portanto, isto permite
|
código Hy em árvore sintática abstrata Python (ast). Portanto, isto permite
|
||||||
hy chamar código python nativo e vice-versa.
|
Hy chamar código Python nativo e vice-versa.
|
||||||
|
|
||||||
Este tutorial funciona para hy ≥ 0.9.12
|
```hylang
|
||||||
|
;; Isso dá uma introdução básica em Hy, como uma preliminar para o link abaixo
|
||||||
```clojure
|
;; https://hylang.org/try-hy
|
||||||
;; Isso dá uma introdução básica em hy, como uma preliminar para o link abaixo
|
|
||||||
;; http://try-hy.appspot.com
|
|
||||||
;;
|
;;
|
||||||
; Comentários em ponto-e-vírgula, como em outros LISPS
|
; Comentários em ponto-e-vírgula, como em outros Lisps
|
||||||
|
|
||||||
;; s-noções básicas de expressão
|
;; s-noções básicas de expressão
|
||||||
; programas Lisp são feitos de expressões simbólicas ou sexps que se assemelham
|
; programas Lisp são feitos de expressões simbólicas ou sexps que se assemelham
|
||||||
@ -28,7 +26,7 @@ Este tutorial funciona para hy ≥ 0.9.12
|
|||||||
|
|
||||||
;; Tipos de dados simples
|
;; Tipos de dados simples
|
||||||
; Todos os tipos de dados simples são exatamente semelhantes aos seus homólogos
|
; Todos os tipos de dados simples são exatamente semelhantes aos seus homólogos
|
||||||
; em python que
|
; em Python que
|
||||||
42 ; => 42
|
42 ; => 42
|
||||||
3.14 ; => 3.14
|
3.14 ; => 3.14
|
||||||
True ; => True
|
True ; => True
|
||||||
@ -36,13 +34,13 @@ True ; => True
|
|||||||
|
|
||||||
; Vamos começar com um pouco de aritmética muito simples
|
; Vamos começar com um pouco de aritmética muito simples
|
||||||
(+ 4 1) ;=> 5
|
(+ 4 1) ;=> 5
|
||||||
; o operador é aplicado a todos os argumentos, como outros lisps
|
; o operador é aplicado a todos os argumentos, como outros Lisps
|
||||||
(+ 4 1 2 3) ;=> 10
|
(+ 4 1 2 3) ;=> 10
|
||||||
(- 2 1) ;=> 1
|
(- 2 1) ;=> 1
|
||||||
(* 4 2) ;=> 8
|
(* 4 2) ;=> 8
|
||||||
(/ 4 1) ;=> 4
|
(/ 4 1) ;=> 4
|
||||||
(% 4 2) ;=> 0 o operador módulo
|
(% 4 2) ;=> 0 o operador módulo
|
||||||
; exponenciação é representado pelo operador ** como python
|
; exponenciação é representado pelo operador ** como Python
|
||||||
(** 3 2) ;=> 9
|
(** 3 2) ;=> 9
|
||||||
; formas aninhadas vão fazer a coisa esperada
|
; formas aninhadas vão fazer a coisa esperada
|
||||||
(+ 2 (* 4 2)) ;=> 10
|
(+ 2 (* 4 2)) ;=> 10
|
||||||
@ -58,9 +56,9 @@ True ; => True
|
|||||||
(def *foo* 42)
|
(def *foo* 42)
|
||||||
;; outros tipos de dados de armazenamento
|
;; outros tipos de dados de armazenamento
|
||||||
; strings, lists, tuples & dicts
|
; strings, lists, tuples & dicts
|
||||||
; estes são exatamente os mesmos tipos de armazenamento de python
|
; estes são exatamente os mesmos tipos de armazenamento de Python
|
||||||
"hello world" ;=> "hello world"
|
"hello world" ;=> "hello world"
|
||||||
; operações de string funcionam semelhante em python
|
; operações de string funcionam semelhante em Python
|
||||||
(+ "hello " "world") ;=> "hello world"
|
(+ "hello " "world") ;=> "hello world"
|
||||||
; Listas são criadas usando [], a indexação começa em 0
|
; Listas são criadas usando [], a indexação começa em 0
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
@ -68,7 +66,7 @@ True ; => True
|
|||||||
(setv mytuple (, 1 2))
|
(setv mytuple (, 1 2))
|
||||||
; dicionários são pares de valores-chave
|
; dicionários são pares de valores-chave
|
||||||
(setv dict1 {"key1" 42 "key2" 21})
|
(setv dict1 {"key1" 42 "key2" 21})
|
||||||
; :nome pode ser utilizado para definir palavras-chave em hy que podem ser utilizados para as chaves
|
; :nome pode ser utilizado para definir palavras-chave em Hy que podem ser utilizados para as chaves
|
||||||
(setv dict2 {:key1 41 :key2 20})
|
(setv dict2 {:key1 41 :key2 20})
|
||||||
; usar 'get' para obter o elemento em um índice/key
|
; usar 'get' para obter o elemento em um índice/key
|
||||||
(get mylist 1) ;=> 2
|
(get mylist 1) ;=> 2
|
||||||
@ -96,19 +94,19 @@ True ; => True
|
|||||||
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
||||||
|
|
||||||
;; operações de sequência
|
;; operações de sequência
|
||||||
; hy tem algumas utils embutidas para operações de sequência, etc.
|
; Hy tem algumas utils embutidas para operações de sequência, etc.
|
||||||
; recuperar o primeiro elemento usando 'first' ou 'car'
|
; recuperar o primeiro elemento usando 'first' ou 'car'
|
||||||
(setv mylist [1 2 3 4])
|
(setv mylist [1 2 3 4])
|
||||||
(setv mydict {"a" 1 "b" 2})
|
(setv mydict {"a" 1 "b" 2})
|
||||||
(first mylist) ;=> 1
|
(first mylist) ;=> 1
|
||||||
|
|
||||||
; corte listas usando 'slice'
|
; corte listas usando 'cut'
|
||||||
(slice mylist 1 3) ;=> [2 3]
|
(cut mylist 1 3) ;=> [2 3]
|
||||||
|
|
||||||
; obter elementos de uma lista ou dict usando 'get'
|
; obter elementos de uma lista ou dict usando 'get'
|
||||||
(get mylist 1) ;=> 2
|
(get mylist 1) ;=> 2
|
||||||
(get mydict "b") ;=> 2
|
(get mydict "b") ;=> 2
|
||||||
; lista de indexação começa a partir de 0, igual em python
|
; lista de indexação começa a partir de 0, igual em Python
|
||||||
; assoc pode definir elementos em chaves/índices
|
; assoc pode definir elementos em chaves/índices
|
||||||
(assoc mylist 2 10) ; faz mylist [1 2 10 4]
|
(assoc mylist 2 10) ; faz mylist [1 2 10 4]
|
||||||
(assoc mydict "c" 3) ; faz mydict {"a" 1 "b" 2 "c" 3}
|
(assoc mydict "c" 3) ; faz mydict {"a" 1 "b" 2 "c" 3}
|
||||||
@ -116,11 +114,11 @@ True ; => True
|
|||||||
; sequências uma diversão
|
; sequências uma diversão
|
||||||
|
|
||||||
;; Python interop
|
;; Python interop
|
||||||
;; importação funciona exatamente como em python
|
;; importação funciona exatamente como em Python
|
||||||
(import datetime)
|
(import datetime)
|
||||||
(import [functools [partial reduce]]) ; importa fun1 e fun2 do module1
|
(import functools [partial reduce]) ; importa fun1 e fun2 do module1
|
||||||
(import [matplotlib.pyplot :as plt]) ; fazendo uma importação em foo como em bar
|
(import matplotlib.pyplot :as plt) ; fazendo uma importação em foo como em bar
|
||||||
; todos os métodos de python embutidas etc. são acessíveis a partir hy
|
; todos os métodos de Python embutidas etc. são acessíveis a partir Hy
|
||||||
; a.foo(arg) is called as (.foo a arg)
|
; a.foo(arg) is called as (.foo a arg)
|
||||||
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
||||||
|
|
||||||
@ -132,12 +130,9 @@ True ; => True
|
|||||||
|
|
||||||
; aninhe múltiplas cláusulas 'if else if' com cond
|
; aninhe múltiplas cláusulas 'if else if' com cond
|
||||||
(cond
|
(cond
|
||||||
[(= someval 42)
|
(= someval 42) (print "Life, universe and everything else!")
|
||||||
(print "Life, universe and everything else!")]
|
(> someval 42) (print "val too large")
|
||||||
[(> someval 42)
|
(< someval 42) (print "val too small"))
|
||||||
(print "val too large")]
|
|
||||||
[(< someval 42)
|
|
||||||
(print "val too small")])
|
|
||||||
|
|
||||||
; declarações de grupo com 'do', essas são executadas sequencialmente
|
; declarações de grupo com 'do', essas são executadas sequencialmente
|
||||||
; formas como defn tem um 'do' implícito
|
; formas como defn tem um 'do' implícito
|
||||||
@ -151,26 +146,24 @@ True ; => True
|
|||||||
"sherlock" "moriarty"
|
"sherlock" "moriarty"
|
||||||
"seinfeld" "newman"}]]
|
"seinfeld" "newman"}]]
|
||||||
(for [(, h v) (.items nemesis)]
|
(for [(, h v) (.items nemesis)]
|
||||||
(print (.format "{0}'s nemesis was {1}" h v))))
|
(print (.format "{0}'s nemesis was {1}" h v))))
|
||||||
|
|
||||||
;; classes
|
;; classes
|
||||||
; classes são definidas da seguinte maneira
|
; classes são definidas da seguinte maneira
|
||||||
(defclass Wizard [object]
|
(defclass Wizard [object]
|
||||||
[[--init-- (fn [self spell]
|
(defn __init__ [self spell]
|
||||||
(setv self.spell spell) ; init a mágica attr
|
(setv self.spell spell)) ; init a mágica attr
|
||||||
None)]
|
|
||||||
[get-spell (fn [self]
|
|
||||||
self.spell)]])
|
|
||||||
|
|
||||||
;; acesse hylang.org
|
(defn get-spell [self]
|
||||||
|
self.spell))
|
||||||
```
|
```
|
||||||
|
|
||||||
### Outras Leituras
|
### Outras Leituras
|
||||||
|
|
||||||
Este tutorial é apenas uma introdução básica para hy/lisp/python.
|
Este tutorial é apenas uma introdução básica para Hy/Lisp/Python.
|
||||||
|
|
||||||
Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org)
|
Docs Hy: [https://hylang.org/hy/doc](https://hylang.org/hy/doc)
|
||||||
|
|
||||||
Repo Hy no GitHub: [http://github.com/hylang/hy](http://github.com/hylang/hy)
|
Repo Hy no GitHub: [https://github.com/hylang/hy](https://github.com/hylang/hy)
|
||||||
|
|
||||||
Acesso ao freenode irc com #hy, hashtag no twitter: #hylang
|
Acesso ao freenode irc com #hy, hashtag no twitter: #hylang
|
||||||
|
Loading…
Reference in New Issue
Block a user