.\" Man page generated from reStructuredText. . .TH "HY" "1" "January 16, 2016" "0.11" "hy" .SH NAME hy \- hy Documentation . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. [image: Hy] [image] .INDENT 0.0 .TP .B Try Hy \fI\%https://try\-hy.appspot.com\fP .TP .B PyPI \fI\%https://pypi.python.org/pypi/hy\fP .TP .B Source \fI\%https://github.com/hylang/hy\fP .TP .B List \fI\%hylang\-discuss\fP .TP .B IRC \fB#hy\fP on Freenode .TP .B Build status \fI\%Travis CI\fP.UNINDENT .sp Hy is a wonderful dialect of Lisp that\(aqs embedded in Python. .sp Since Hy transforms its Lisp code into the Python Abstract Syntax Tree, you have the whole beautiful world of Python at your fingertips, in Lisp form! .sp Contents: .SH QUICKSTART [image: Karen Rustard's Cuddles] [image] .sp (Thanks to Karen Rustad for Cuddles!) .sp \fBHOW TO GET HY REAL FAST\fP: .INDENT 0.0 .IP 1. 3 Create a \fI\%Virtual Python Environment\fP\&. .IP 2. 3 Activate your Virtual Python Environment. .IP 3. 3 Install \fI\%hy from PyPI\fP with \fBpip install hy\fP\&. .IP 4. 3 Start a REPL with \fBhy\fP\&. .IP 5. 3 Type stuff in the REPL: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C => (print "Hy!") Hy! => (defn salutationsnm [name] (print (+ "Hy " name "!"))) => (salutationsnm "YourName") Hy YourName! etc .ft P .fi .UNINDENT .UNINDENT .IP 6. 3 Hit CTRL\-D when you\(aqre done. .UNINDENT .sp \fIOMG! That\(aqs amazing! I want to write a Hy program.\fP .INDENT 0.0 .IP 7. 3 Open up an elite programming editor and type: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C (print "I was going to code in Python syntax, but then I got Hy.") .ft P .fi .UNINDENT .UNINDENT .IP 8. 3 Save as \fBawesome.hy\fP\&. .IP 9. 3 And run your first Hy program: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C hy awesome.hy .ft P .fi .UNINDENT .UNINDENT .IP 10. 3 Take a deep breath so as to not hyperventilate. .IP 11. 3 Smile villainously and sneak off to your hydeaway and do unspeakable things. .UNINDENT .SH TUTORIAL .sp Welcome to the Hy tutorial! .sp In a nutshell, Hy is a Lisp dialect, but one that converts its structure into Python ... literally a conversion into Python\(aqs abstract syntax tree! (Or to put it in more crude terms, Hy is lisp\-stick on a Python!) .sp This is pretty cool because it means Hy is several things: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 A Lisp that feels very Pythonic .IP \(bu 2 For Lispers, a great way to use Lisp\(aqs crazy powers but in the wide world of Python\(aqs libraries (why yes, you now can write a Django application in Lisp!) .IP \(bu 2 For Pythonistas, a great way to start exploring Lisp, from the comfort of Python! .IP \(bu 2 For everyone: a pleasant language that has a lot of neat ideas! .UNINDENT .UNINDENT .UNINDENT .SS Basic intro to Lisp for Pythonistas .sp Okay, maybe you\(aqve never used Lisp before, but you\(aqve used Python! .sp A "hello world" program in Hy is actually super simple. Let\(aqs try it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "hello world") .ft P .fi .UNINDENT .UNINDENT .sp See? Easy! As you may have guessed, this is the same as the Python version of: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C print "hello world" .ft P .fi .UNINDENT .UNINDENT .sp To add up some super simple math, we could do: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (+ 1 3) .ft P .fi .UNINDENT .UNINDENT .sp Which would return 4 and would be the equivalent of: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 1 + 3 .ft P .fi .UNINDENT .UNINDENT .sp What you\(aqll notice is that the first item in the list is the function being called and the rest of the arguments are the arguments being passed in. In fact, in Hy (as with most Lisps) we can pass in multiple arguments to the plus operator: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (+ 1 3 55) .ft P .fi .UNINDENT .UNINDENT .sp Which would return 59. .sp Maybe you\(aqve heard of Lisp before but don\(aqt know much about it. Lisp isn\(aqt as hard as you might think, and Hy inherits from Python, so Hy is a great way to start learning Lisp. The main thing that\(aqs obvious about Lisp is that there\(aqs a lot of parentheses. This might seem confusing at first, but it isn\(aqt so hard. Let\(aqs look at some simple math that\(aqs wrapped in a bunch of parentheses that we could enter into the Hy interpreter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv result (\- (/ (+ 1 3 88) 2) 8)) .ft P .fi .UNINDENT .UNINDENT .sp This would return 38. But why? Well, we could look at the equivalent expression in python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C result = ((1 + 3 + 88) / 2) \- 8 .ft P .fi .UNINDENT .UNINDENT .sp If you were to try to figure out how the above were to work in python, you\(aqd of course figure out the results by solving each inner parenthesis. That\(aqs the same basic idea in Hy. Let\(aqs try this exercise first in Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C result = ((1 + 3 + 88) / 2) \- 8 # simplified to... result = (92 / 2) \- 8 # simplified to... result = 46 \- 8 # simplified to... result = 38 .ft P .fi .UNINDENT .UNINDENT .sp Now let\(aqs try the same thing in Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv result (\- (/ (+ 1 3 88) 2) 8)) ; simplified to... (setv result (\- (/ 92 2) 8)) ; simplified to... (setv result (\- 46 8)) ; simplified to... (setv result 38) .ft P .fi .UNINDENT .UNINDENT .sp As you probably guessed, this last expression with \fBsetv\fP means to assign the variable "result" to 38. .sp See? Not too hard! .sp This is the basic premise of Lisp. Lisp stands for "list processing"; this means that the structure of the program is actually lists of lists. (If you\(aqre familiar with Python lists, imagine the entire same structure as above but with square brackets instead, any you\(aqll be able to see the structure above as both a program and a datastructure.) This is easier to understand with more examples, so let\(aqs write a simple Python program, test it, and then show the equivalent Hy program: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def simple_conversation(): print "Hello! I\(aqd like to get to know you. Tell me about yourself!" name = raw_input("What is your name? ") age = raw_input("What is your age? ") print "Hello " + name + "! I see you are " + age + " years old." simple_conversation() .ft P .fi .UNINDENT .UNINDENT .sp If we ran this program, it might go like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Hello! I\(aqd like to get to know you. Tell me about yourself! What is your name? Gary What is your age? 38 Hello Gary! I see you are 38 years old. .ft P .fi .UNINDENT .UNINDENT .sp Now let\(aqs look at the equivalent Hy program: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn simple\-conversation [] (print "Hello! I\(aqd like to get to know you. Tell me about yourself!") (setv name (raw\-input "What is your name? ")) (setv age (raw\-input "What is your age? ")) (print (+ "Hello " name "! I see you are " age " years old."))) (simple\-conversation) .ft P .fi .UNINDENT .UNINDENT .sp If you look at the above program, as long as you remember that the first element in each list of the program is the function (or macro... we\(aqll get to those later) being called and that the rest are the arguments, it\(aqs pretty easy to figure out what this all means. (As you probably also guessed, \fBdefn\fP is the Hy method of defining methods.) .sp Still, lots of people find this confusing at first because there\(aqs so many parentheses, but there are plenty of things that can help make this easier: keep indentation nice and use an editor with parenthesis matching (this will help you figure out what each parenthesis pairs up with) and things will start to feel comfortable. .sp There are some advantages to having a code structure that\(aqs actually a very simple data structure as the core of Lisp is based on. For one thing, it means that your programs are easy to parse and that the entire actual structure of the program is very clearly exposed to you. (There\(aqs an extra step in hy where the structure you see is converted to Python\(aqs own representations ... in "purer" Lisps such as Common Lisp or Emacs Lisp, the data structure you see in the code and the data structure that is executed is much more literally close.) .sp Another implication of this is macros: if a program\(aqs structure is a simple data structure, that means you can write code that can write code very easily, meaning that implementing entirely new language features can be very fast. Previous to Hy, this wasn\(aqt very possible for Python programmers ... now you too can make use of macros\(aq incredible power (just be careful to not aim them footward)! .SS Hy is a Lisp\-flavored Python .sp Hy converts to Python\(aqs own abstract syntax tree, so you\(aqll soon start to find that all the familiar power of python is at your fingertips. .sp You have full access to Python\(aqs data types and standard library in Hy. Let\(aqs experiment with this in the hy interpreter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => [1 2 3] [1, 2, 3] => {"dog" "bark" \&... "cat" "meow"} \&... {\(aqdog\(aq: \(aqbark\(aq, \(aqcat\(aq: \(aqmeow\(aq} => (, 1 2 3) (1, 2, 3) .ft P .fi .UNINDENT .UNINDENT .sp If you are familiar with other Lisps, you may be interested that Hy supports the Common Lisp method of quoting: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => \(aq(1 2 3) (1L 2L 3L) .ft P .fi .UNINDENT .UNINDENT .sp You also have access to all the built\-in types\(aq nice methods: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (.strip " fooooo ") "fooooo" .ft P .fi .UNINDENT .UNINDENT .sp What\(aqs this? Yes indeed, this is precisely the same as: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C " fooooo ".strip() .ft P .fi .UNINDENT .UNINDENT .sp That\(aqs right\-\-\-Lisp with dot notation! If we have this string assigned as a variable, we can also do the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv this\-string " fooooo ") (this\-string.strip) .ft P .fi .UNINDENT .UNINDENT .sp What about conditionals?: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (if (try\-some\-thing) (print "this is if true") (print "this is if false")) .ft P .fi .UNINDENT .UNINDENT .sp As you can tell above, the first argument to \fBif\fP is a truth test, the second argument is the body if true, and the third argument (optional!) is if false (ie. \fBelse\fP). .sp If you need to do more complex conditionals, you\(aqll find that you don\(aqt have \fBelif\fP available in Hy. Instead, you should use something called \fBcond\fP\&. In Python, you might do something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C somevar = 33 if somevar > 50: print "That variable is too big!" elif somevar < 10: print "That variable is too small!" else: print "That variable is jussssst right!" .ft P .fi .UNINDENT .UNINDENT .sp In Hy, you would do: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (cond [(> somevar 50) (print "That variable is too big!")] [(< somevar 10) (print "That variable is too small!")] [true (print "That variable is jussssst right!")]) .ft P .fi .UNINDENT .UNINDENT .sp What you\(aqll notice is that \fBcond\fP switches off between a some statement that is executed and checked conditionally for true or falseness, and then a bit of code to execute if it turns out to be true. You\(aqll also notice that the \fBelse\fP is implemented at the end simply by checking for \fBtrue\fP \-\- that\(aqs because \fBtrue\fP will always be true, so if we get this far, we\(aqll always run that one! .sp You might notice above that if you have code like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (if some\-condition (body\-if\-true) (body\-if\-false)) .ft P .fi .UNINDENT .UNINDENT .sp But wait! What if you want to execute more than one statement in the body of one of these? .sp You can do the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (if (try\-some\-thing) (do (print "this is if true") (print "and why not, let\(aqs keep talking about how true it is!)) (print "this one\(aqs still simply just false")) .ft P .fi .UNINDENT .UNINDENT .sp You can see that we used \fBdo\fP to wrap multiple statements. If you\(aqre familiar with other Lisps, this is the equivalent of \fBprogn\fP elsewhere. .sp Comments start with semicolons: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "this will run") ; (print "but this will not") (+ 1 2 3) ; we\(aqll execute the addition, but not this comment! .ft P .fi .UNINDENT .UNINDENT .sp Looping is not hard but has a kind of special structure. In Python, we might do: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for i in range(10): print "\(aqi\(aq is now at " + str(i) .ft P .fi .UNINDENT .UNINDENT .sp The equivalent in Hy would be: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (for [i (range 10)] (print (+ "\(aqi\(aq is now at " (str i)))) .ft P .fi .UNINDENT .UNINDENT .sp You can also import and make use of various Python libraries. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import os) (if (os.path.isdir "/tmp/somedir") (os.mkdir "/tmp/somedir/anotherdir") (print "Hey, that path isn\(aqt there!")) .ft P .fi .UNINDENT .UNINDENT .sp Python\(aqs context managers (\fBwith\fP statements) are used like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with [[f (open "/tmp/data.in")]] (print (.read f))) .ft P .fi .UNINDENT .UNINDENT .sp which is equivalent to: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C with open("/tmp/data.in") as f: print f.read() .ft P .fi .UNINDENT .UNINDENT .sp And yes, we do have List comprehensions! In Python you might do: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C odds_squared = [ pow(num, 2) for num in range(100) if num % 2 == 1] .ft P .fi .UNINDENT .UNINDENT .sp In Hy, you could do these like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv odds\-squared (list\-comp (pow num 2) (num (range 100)) (= (% num 2) 1))) .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ; And, an example stolen shamelessly from a Clojure page: ; Let\(aqs list all the blocks of a Chessboard: (list\-comp (, x y) (x (range 8) y "ABCDEFGH")) ; [(0, \(aqA\(aq), (0, \(aqB\(aq), (0, \(aqC\(aq), (0, \(aqD\(aq), (0, \(aqE\(aq), (0, \(aqF\(aq), (0, \(aqG\(aq), (0, \(aqH\(aq), ; (1, \(aqA\(aq), (1, \(aqB\(aq), (1, \(aqC\(aq), (1, \(aqD\(aq), (1, \(aqE\(aq), (1, \(aqF\(aq), (1, \(aqG\(aq), (1, \(aqH\(aq), ; (2, \(aqA\(aq), (2, \(aqB\(aq), (2, \(aqC\(aq), (2, \(aqD\(aq), (2, \(aqE\(aq), (2, \(aqF\(aq), (2, \(aqG\(aq), (2, \(aqH\(aq), ; (3, \(aqA\(aq), (3, \(aqB\(aq), (3, \(aqC\(aq), (3, \(aqD\(aq), (3, \(aqE\(aq), (3, \(aqF\(aq), (3, \(aqG\(aq), (3, \(aqH\(aq), ; (4, \(aqA\(aq), (4, \(aqB\(aq), (4, \(aqC\(aq), (4, \(aqD\(aq), (4, \(aqE\(aq), (4, \(aqF\(aq), (4, \(aqG\(aq), (4, \(aqH\(aq), ; (5, \(aqA\(aq), (5, \(aqB\(aq), (5, \(aqC\(aq), (5, \(aqD\(aq), (5, \(aqE\(aq), (5, \(aqF\(aq), (5, \(aqG\(aq), (5, \(aqH\(aq), ; (6, \(aqA\(aq), (6, \(aqB\(aq), (6, \(aqC\(aq), (6, \(aqD\(aq), (6, \(aqE\(aq), (6, \(aqF\(aq), (6, \(aqG\(aq), (6, \(aqH\(aq), ; (7, \(aqA\(aq), (7, \(aqB\(aq), (7, \(aqC\(aq), (7, \(aqD\(aq), (7, \(aqE\(aq), (7, \(aqF\(aq), (7, \(aqG\(aq), (7, \(aqH\(aq)] .ft P .fi .UNINDENT .UNINDENT .sp Python has support for various fancy argument and keyword arguments. In Python we might see: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> def optional_arg(pos1, pos2, keyword1=None, keyword2=42): \&... return [pos1, pos2, keyword1, keyword2] \&... >>> optional_arg(1, 2) [1, 2, None, 42] >>> optional_arg(1, 2, 3, 4) [1, 2, 3, 4] >>> optional_arg(keyword1=1, pos2=2, pos1=3, keyword2=4) [3, 2, 1, 4] .ft P .fi .UNINDENT .UNINDENT .sp The same thing in Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn optional\-arg [pos1 pos2 &optional keyword1 [keyword2 42]] \&... [pos1 pos2 keyword1 keyword2]) => (optional\-arg 1 2) [1 2 None 42] => (optional\-arg 1 2 3 4) [1 2 3 4] .ft P .fi .UNINDENT .UNINDENT .sp If you\(aqre running a version of Hy past 0.10.1 (eg, git master), there\(aqs also a nice new keyword argument syntax: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (optional\-arg :keyword1 1 \&... :pos2 2 \&... :pos1 3 \&... :keyword2 4) [3, 2, 1, 4] .ft P .fi .UNINDENT .UNINDENT .sp Otherwise, you can always use \fIapply\fP\&. But what\(aqs \fIapply\fP? .sp Are you familiar with passing in \fI*args\fP and \fI**kwargs\fP in Python?: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> args = [1 2] >>> kwargs = {"keyword2": 3 \&... "keyword1": 4} >>> optional_arg(*args, **kwargs) .ft P .fi .UNINDENT .UNINDENT .sp We can reproduce this with \fIapply\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv args [1 2]) => (setv kwargs {"keyword2" 3 \&... "keyword1" 4}) => (apply optional\-arg args kwargs) [1, 2, 4, 3] .ft P .fi .UNINDENT .UNINDENT .sp There\(aqs also a dictionary\-style keyword arguments construction that looks like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn another\-style [&key {"key1" "val1" "key2" "val2"}] [key1 key2]) .ft P .fi .UNINDENT .UNINDENT .sp The difference here is that since it\(aqs a dictionary, you can\(aqt rely on any specific ordering to the arguments. .sp Hy also supports \fB*args\fP and \fB**kwargs\fP\&. In Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def some_func(foo, bar, *args, **kwargs): import pprint pprint.pprint((foo, bar, args, kwargs)) .ft P .fi .UNINDENT .UNINDENT .sp The Hy equivalent: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn some\-func [foo bar &rest args &kwargs kwargs] (import pprint) (pprint.pprint (, foo bar args kwargs))) .ft P .fi .UNINDENT .UNINDENT .sp Finally, of course we need classes! In Python, we might have a class like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class FooBar(object): """ Yet Another Example Class """ def __init__(self, x): self.x = x def get_x(self): """ Return our copy of x """ return self.x .ft P .fi .UNINDENT .UNINDENT .sp In Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defclass FooBar [object] "Yet Another Example Class" [[\-\-init\-\- (fn [self x] (setv self.x x) ; Currently needed for \-\-init\-\- because __init__ needs None ; Hopefully this will go away :) None)] [get\-x (fn [self] "Return our copy of x" self.x)]]) .ft P .fi .UNINDENT .UNINDENT .sp You can also do class\-level attributes. In Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class Customer(models.Model): name = models.CharField(max_length=255) address = models.TextField() notes = models.TextField() .ft P .fi .UNINDENT .UNINDENT .sp In Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defclass Customer [models.Model] [[name (models.CharField :max\-length 255})] [address (models.TextField)] [notes (models.TextField)]]) .ft P .fi .UNINDENT .UNINDENT .SS Hy <\-> Python interop .sp By importing Hy, you can use Hy directly from Python! .sp If you save the following in \fBgreetings.hy\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn greet [name] (print "hello from hy," name)) .ft P .fi .UNINDENT .UNINDENT .sp Then you can use it directly from python, by importing hy before importing the module. In Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import hy import greetings greetings.greet("Foo") .ft P .fi .UNINDENT .UNINDENT .sp You can also declare a function in python (or even a class!) and use it in Hy! .sp If you save the following in \fBgreetings.py\fP in Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def greet(name): print("hello, %s" % (name)) .ft P .fi .UNINDENT .UNINDENT .sp You can use it in Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import greetings) (.greet greetings "foo") .ft P .fi .UNINDENT .UNINDENT .sp To use keyword arguments, you can use in \fBgreetings.py\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def greet(name, title="Sir"): print("Greetings, %s %s" % (title,name)) .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import greetings) (.greet greetings "Foo") (.greet greetings "Foo" "Darth") (apply (. greetings greet) ["Foo"] {"title" "Lord"}) .ft P .fi .UNINDENT .UNINDENT .sp Which would output: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Greetings, Sir Foo Greetings, Darth Foo Greetings, Lord Foo .ft P .fi .UNINDENT .UNINDENT .SS Protips! .sp Hy also features something known as the "threading macro", a really neat feature of Clojure\(aqs. The "threading macro" (written as \fB\->\fP) is used to avoid deep nesting of expressions. .sp The threading macro inserts each expression into the next expression\(aqs first argument place. .sp Let\(aqs take the classic: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (loop (print (eval (read)))) .ft P .fi .UNINDENT .UNINDENT .sp Rather than write it like that, we can write it as follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (\-> (read) (eval) (print) (loop)) .ft P .fi .UNINDENT .UNINDENT .sp Now, using \fI\%python\-sh\fP, we can show how the threading macro (because of python\-sh\(aqs setup) can be used like a pipe: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import [sh [cat grep wc]]) => (\-> (cat "/usr/share/dict/words") (grep "\-E" "^hy") (wc "\-l")) 210 .ft P .fi .UNINDENT .UNINDENT .sp Which, of course, expands out to: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (wc (grep (cat "/usr/share/dict/words") "\-E" "^hy") "\-l") .ft P .fi .UNINDENT .UNINDENT .sp Much more readable, no? Use the threading macro! .SH HY STYLE GUIDE .INDENT 0.0 .INDENT 3.5 “You know, Minister, I disagree with Dumbledore on many counts…but you cannot deny he’s got style…” — Phineas Nigellus Black, \fIHarry Potter and the Order of the Phoenix\fP .UNINDENT .UNINDENT .sp The Hy style guide intends to be a set of ground rules for the Hyve (yes, the Hy community prides itself in appending Hy to everything) to write idiomatic Hy code. Hy derives a lot from Clojure & Common Lisp, while always maintaining Python interopability. .SS Prelude .SS The Tao of Hy .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ummon asked the head monk, "What sutra are you lecturing on?" "The Nirvana Sutra." "The Nirvana Sutra has the Four Virtues, hasn\(aqt it?" "It has." Ummon asked, picking up a cup, "How many virtues has this?" "None at all," said the monk. "But ancient people said it had, didn\(aqt they?" said Ummon. "What do you think of what they said?" Ummon struck the cup and asked, "You understand?" "No," said the monk. "Then," said Ummon, "You\(aqd better go on with your lectures on the sutra." — the (koan) macro .ft P .fi .UNINDENT .UNINDENT .sp The following illustrates a brief list of design decisions that went into the making of Hy. .INDENT 0.0 .IP \(bu 2 Look like a Lisp; DTRT with it (e.g. dashes turn to underscores, earmuffs turn to all\-caps). .IP \(bu 2 We\(aqre still Python. Most of the internals translate 1:1 to Python internals. .IP \(bu 2 Use Unicode everywhere. .IP \(bu 2 Fix the bad decisions in Python 2 when we can (see \fBtrue_division\fP). .IP \(bu 2 When in doubt, defer to Python. .IP \(bu 2 If you\(aqre still unsure, defer to Clojure. .IP \(bu 2 If you\(aqre even more unsure, defer to Common Lisp. .IP \(bu 2 Keep in mind we\(aqre not Clojure. We\(aqre not Common Lisp. We\(aqre Homoiconic Python, with extra bits that make sense. .UNINDENT .SS Layout & Indentation .INDENT 0.0 .IP \(bu 2 Avoid trailing spaces. They suck! .IP \(bu 2 Indentation shall be 2 spaces (no hard tabs), except when matching the indentation of the previous line. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C ;; Good (and preferred) (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; Still okay (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; Still okay (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; Hysterically ridiculous (defn fib [n] (if (<= n 2) n ;; yes, I love randomly hitting the space key (+ (fib (\- n 1)) (fib (\- n 2))))) .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Parentheses must \fInever\fP be left alone, sad and lonesome on their own line. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C ;; Good (and preferred) (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; Hysterically ridiculous (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))) ) ) ; GAH, BURN IT WITH FIRE .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Vertically align \fBlet\fP blocks. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C (let [[foo (bar)] [qux (baz)]] (foo qux)) .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Inline comments shall be two spaces from the end of the code; they must always have a space between the comment character and the start of the comment. Also, try to not comment the obvious. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; Good (setv ind (dec x)) ; indexing starts from 0 ;; Style\-compliant but just states the obvious (setv ind (dec x)) ; sets index to x\-1 ;; Bad (setv ind (dec x));typing words for fun .ft P .fi .UNINDENT .UNINDENT .SS Coding Style .INDENT 0.0 .IP \(bu 2 As a convention, try not to use \fBdef\fP for anything other than global variables; use \fBsetv\fP inside functions, loops, etc. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C ;; Good (and preferred) (def *limit* 400000) (defn fibs [a b] (while true (yield a) (setv (, a b) (, b (+ a b))))) ;; Bad (and not preferred) (defn fibs [a b] (while true (yield a) (def (, a b) (, b (+ a b))))) .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Do not use s\-expression syntax where vector syntax is intended. For instance, the fact that the former of these two examples works is just because the compiler isn\(aqt overly strict. In reality, the correct syntax in places such as this is the latter. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C ;; Bad (and evil) (defn foo (x) (print x)) (foo 1) ;; Good (and preferred) (defn foo [x] (print x)) (foo 1) .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Use the threading macro or the threading tail macros when encountering deeply nested s\-expressions. However, be judicious when using them. Do use them when clarity and readability improves; do not construct convoluted, hard to understand expressions. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C ;; Preferred (def *names* (with [f (open "names.txt")] (\-> (.read f) (.strip) (.replace "\e"" "") (.split ",") (sorted)))) ;; Not so good (def *names* (with [f (open "names.txt")] (sorted (.split "," (.replace "\e"" "" (.strip (.read f))))))) ;; Probably not a good idea (defn square? [x] (\->> 2 (pow (int (sqrt x))) (= x))) .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Clojure\-style dot notation is preferred over the direct call of the object\(aqs method, though both will continue to be supported. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C ;; Good (with [fd (open "/etc/passwd")] (print (.readlines fd))) ;; Not so good (with [fd (open "/etc/passwd")] (print (fd.readlines))) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SS Conclusion .INDENT 0.0 .INDENT 3.5 “Fashions fade, style is eternal” —Yves Saint Laurent .UNINDENT .UNINDENT .sp This guide is just a set of community guidelines, and obviously, community guidelines do not make sense without an active community. Contributions are welcome. Join us at #hy in freenode, blog about it, tweet about it, and most importantly, have fun with Hy. .SS Thanks .INDENT 0.0 .IP \(bu 2 This guide is heavily inspired from \fI\%@paultag\fP \(aqs blog post \fI\%Hy Survival Guide\fP .IP \(bu 2 The \fI\%Clojure Style Guide\fP .UNINDENT .SH DOCUMENTATION INDEX .sp Contents: .SS Command Line Interface .SS hy .SS Command Line Options .INDENT 0.0 .TP .B \-c Execute the Hy code in \fIcommand\fP\&. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C $ hy \-c "(print (+ 2 2))" 4 .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B \-i Execute the Hy code in \fIcommand\fP, then stay in REPL. .UNINDENT .INDENT 0.0 .TP .B \-m Execute the Hy code in \fImodule\fP, including \fBdefmain\fP if defined. .sp The \fI\%\-m\fP flag terminates the options list so that all arguments after the \fImodule\fP name are passed to the module in \fBsys.argv\fP\&. .sp New in version 0.10.2. .UNINDENT .INDENT 0.0 .TP .B \-\-spy Print equivalent Python code before executing. For example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (defn salutationsnm [name] (print (+ "Hy " name "!"))) def salutationsnm(name): return print(((u\(aqHy \(aq + name) + u\(aq!\(aq)) => (salutationsnm "YourName") salutationsnm(u\(aqYourName\(aq) Hy YourName! => .ft P .fi .UNINDENT .UNINDENT .sp New in version 0.9.11. .UNINDENT .INDENT 0.0 .TP .B \-\-show\-tracebacks Print extended tracebacks for Hy exceptions. .sp New in version 0.9.12. .UNINDENT .INDENT 0.0 .TP .B \-v Print the Hy version number and exit. .UNINDENT .SS hyc .SS Command Line Options .INDENT 0.0 .TP .B file[, fileN] Compile Hy code to Python bytecode. For example, save the following code as \fBhyname.hy\fP: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C (defn hy\-hy [name] (print (+ "Hy " name "!"))) (hy\-hy "Afroman") .ft P .fi .UNINDENT .UNINDENT .sp Then run: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C $ hyc hyname.hy $ python hyname.pyc Hy Afroman! .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SS hy2py .sp New in version 0.10.1. .SS Command Line Options .INDENT 0.0 .TP .B \-s .TP .B \-\-with\-source Show the parsed source structure. .UNINDENT .INDENT 0.0 .TP .B \-a .TP .B \-\-with\-ast Show the generated AST. .UNINDENT .INDENT 0.0 .TP .B \-np .TP .B \-\-without\-python Do not show the Python code generated from the AST. .UNINDENT .SS Hy (the language) .sp \fBWARNING:\fP .INDENT 0.0 .INDENT 3.5 This is incomplete; please consider contributing to the documentation effort. .UNINDENT .UNINDENT .SS Theory of Hy .sp Hy maintains, over everything else, 100% compatibility in both directions with Python itself. All Hy code follows a few simple rules. Memorize this, as it\(aqs going to come in handy. .sp These rules help ensure that Hy code is idiomatic and interfaceable in both languages. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Symbols in earmufs will be translated to the upper\-cased version of that string. For example, \fBfoo\fP will become \fBFOO\fP\&. .IP \(bu 2 UTF\-8 entities will be encoded using \fI\%punycode\fP and prefixed with \fBhy_\fP\&. For instance, \fB⚘\fP will become \fBhy_w7h\fP, \fB♥\fP will become \fBhy_g6h\fP, and \fBi♥u\fP will become \fBhy_iu_t0x\fP\&. .IP \(bu 2 Symbols that contain dashes will have them replaced with underscores. For example, \fBrender\-template\fP will become \fBrender_template\fP\&. This means that symbols with dashes will shadow their underscore equivalents, and vice versa. .UNINDENT .UNINDENT .UNINDENT .SS Built\-Ins .sp Hy features a number of special forms that are used to help generate correct Python AST. The following are "special" forms, which may have behavior that\(aqs slightly unexpected in some situations. .SS \&. .sp New in version 0.10.0. .sp \fB\&.\fP is used to perform attribute access on objects. It uses a small DSL to allow quick access to attributes and items in a nested data structure. .sp For instance, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (. foo bar baz [(+ 1 2)] frob) .ft P .fi .UNINDENT .UNINDENT .sp Compiles down to: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C foo.bar.baz[1 + 2].frob .ft P .fi .UNINDENT .UNINDENT .sp \fB\&.\fP compiles its first argument (in the example, \fIfoo\fP) as the object on which to do the attribute dereference. It uses bare symbols as attributes to access (in the example, \fIbar\fP, \fIbaz\fP, \fIfrob\fP), and compiles the contents of lists (in the example, \fB[(+ 1 2)]\fP) for indexation. Other arguments throw a compilation error. .sp Access to unknown attributes throws an \fBAttributeError\fP\&. Access to unknown keys throws an \fBIndexError\fP (on lists and tuples) or a \fBKeyError\fP (on dictionaries). .SS \-> .sp \fB\->\fP (or the \fIthreading macro\fP) is used to avoid nesting of expressions. The threading macro inserts each expression into the next expression\(aqs first argument place. The following code demonstrates this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn output [a b] (print a b)) => (\-> (+ 4 6) (output 5)) 10 5 .ft P .fi .UNINDENT .UNINDENT .SS \->> .sp \fB\->>\fP (or the \fIthreading tail macro\fP) is similar to the \fIthreading macro\fP, but instead of inserting each expression into the next expression\(aqs first argument, it appends it as the last argument. The following code demonstrates this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn output [a b] (print a b)) => (\->> (+ 4 6) (output 5)) 5 10 .ft P .fi .UNINDENT .UNINDENT .SS apply .sp \fBapply\fP is used to apply an optional list of arguments and an optional dictionary of kwargs to a function. .sp Usage: \fB(apply fn\-name [args] [kwargs])\fP .sp Examples: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn thunk [] "hy there") (apply thunk) ;=> "hy there" (defn total\-purchase [price amount &optional [fees 1.05] [vat 1.1]] (* price amount fees vat)) (apply total\-purchase [10 15]) ;=> 173.25 (apply total\-purchase [10 15] {"vat" 1.05}) ;=> 165.375 (apply total\-purchase [] {"price" 10 "amount" 15 "vat" 1.05}) ;=> 165.375 .ft P .fi .UNINDENT .UNINDENT .SS and .sp \fBand\fP is used in logical expressions. It takes at least two parameters. If all parameters evaluate to \fBTrue\fP, the last parameter is returned. In any other case, the first false value will be returned. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (and True False) False => (and True True) True => (and True 1) 1 => (and True [] False True) [] .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBand\fP short\-circuits and stops evaluating parameters as soon as the first false is encountered. .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (and False (print "hello")) False .ft P .fi .UNINDENT .UNINDENT .SS assert .sp \fBassert\fP is used to verify conditions while the program is running. If the condition is not met, an \fBAssertionError\fP is raised. \fBassert\fP may take one or two parameters. The first parameter is the condition to check, and it should evaluate to either \fBTrue\fP or \fBFalse\fP\&. The second parameter, optional, is a label for the assert, and is the string that will be raised with the \fBAssertionError\fP\&. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (assert (= variable expected\-value)) (assert False) ; AssertionError (assert (= 1 2) "one should equal two") ; AssertionError: one should equal two .ft P .fi .UNINDENT .UNINDENT .SS assoc .sp \fBassoc\fP is used to associate a key with a value in a dictionary or to set an index of a list to a value. It takes at least three parameters: the \fIdata structure\fP to be modified, a \fIkey\fP or \fIindex\fP, and a \fIvalue\fP\&. If more than three parameters are used, it will associate in pairs. .sp Examples of usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C =>(let [[collection {}]] \&... (assoc collection "Dog" "Bark") \&... (print collection)) {u\(aqDog\(aq: u\(aqBark\(aq} =>(let [[collection {}]] \&... (assoc collection "Dog" "Bark" "Cat" "Meow") \&... (print collection)) {u\(aqCat\(aq: u\(aqMeow\(aq, u\(aqDog\(aq: u\(aqBark\(aq} =>(let [[collection [1 2 3 4]]] \&... (assoc collection 2 None) \&... (print collection)) [1, 2, None, 4] .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBassoc\fP modifies the datastructure in place and returns \fBNone\fP\&. .UNINDENT .UNINDENT .SS break .sp \fBbreak\fP is used to break out from a loop. It terminates the loop immediately. The following example has an infinite \fBwhile\fP loop that is terminated as soon as the user enters \fIk\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (while True (if (= "k" (raw\-input "? ")) (break) (print "Try again"))) .ft P .fi .UNINDENT .UNINDENT .SS cond .sp \fBcond\fP can be used to build nested \fBif\fP statements. The following example shows the relationship between the macro and its expansion: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (cond [condition\-1 result\-1] [condition\-2 result\-2]) (if condition\-1 result\-1 (if condition\-2 result\-2)) .ft P .fi .UNINDENT .UNINDENT .sp As shown below, only the first matching result block is executed. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn check\-value [value] \&... (cond [(< value 5) (print "value is smaller than 5")] \&... [(= value 5) (print "value is equal to 5")] \&... [(> value 5) (print "value is greater than 5")] \&... [True (print "value is something that it should not be")])) => (check\-value 6) value is greater than 5 .ft P .fi .UNINDENT .UNINDENT .SS continue .sp \fBcontinue\fP returns execution to the start of a loop. In the following example, \fB(side\-effect1)\fP is called for each iteration. \fB(side\-effect2)\fP, however, is only called on every other value in the list. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; assuming that (side\-effect1) and (side\-effect2) are functions and ;; collection is a list of numerical values (for [x collection] (do (side\-effect1 x) (if (% x 2) (continue)) (side\-effect2 x))) .ft P .fi .UNINDENT .UNINDENT .SS dict\-comp .sp \fBdict\-comp\fP is used to create dictionaries. It takes three or four parameters. The first two parameters are for controlling the return value (key\-value pair) while the third is used to select items from a sequence. The fourth and optional parameter can be used to filter out some of the items in the sequence based on a conditional expression. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (dict\-comp x (* x 2) [x (range 10)] (odd? x)) {1: 2, 3: 6, 9: 18, 5: 10, 7: 14} .ft P .fi .UNINDENT .UNINDENT .SS do / progn .sp \fBdo\fP and \fIprogn\fP are used to evaluate each of their arguments and return the last one. Return values from every other than the last argument are discarded. It can be used in \fBlambda\fP or \fBlist\-comp\fP to perform more complex logic as shown in one of the following examples. .sp Some example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (if true \&... (do (print "Side effects rock!") \&... (print "Yeah, really!"))) Side effects rock! Yeah, really! ;; assuming that (side\-effect) is a function that we want to call for each ;; and every value in the list, but whose return value we do not care about => (list\-comp (do (side\-effect x) \&... (if (< x 5) (* 2 x) \&... (* 4 x))) \&... (x (range 10))) [0, 2, 4, 6, 8, 20, 24, 28, 32, 36] .ft P .fi .UNINDENT .UNINDENT .sp \fBdo\fP can accept any number of arguments, from 1 to n. .SS def / setv .sp \fBdef\fP and \fBsetv\fP are used to bind a value, object, or function to a symbol. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (def names ["Alice" "Bob" "Charlie"]) => (print names) [u\(aqAlice\(aq, u\(aqBob\(aq, u\(aqCharlie\(aq] => (setv counter (fn [collection item] (.count collection item))) => (counter [1 2 3 4 5 2 3] 2) 2 .ft P .fi .UNINDENT .UNINDENT .SS defclass .sp New classes are declared with \fBdefclass\fP\&. It can takes two optional parameters: a vector defining a possible super classes and another vector containing attributes of the new class as two item vectors. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defclass class\-name [super\-class\-1 super\-class\-2] [[attribute value]]) .ft P .fi .UNINDENT .UNINDENT .sp Both values and functions can be bound on the new class as shown by the example below: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defclass Cat [] \&... [[age None] \&... [colour "white"] \&... [speak (fn [self] (print "Meow"))]]) => (def spot (Cat)) => (setv spot.colour "Black") \(aqBlack\(aq => (.speak spot) Meow .ft P .fi .UNINDENT .UNINDENT .SS defn / defun .sp \fBdefn\fP and \fBdefun\fP macros are used to define functions. They take three parameters: the \fIname\fP of the function to define, a vector of \fIparameters\fP, and the \fIbody\fP of the function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn name [params] body) .ft P .fi .UNINDENT .UNINDENT .sp Parameters may have the following keywords in front of them: .INDENT 0.0 .TP .B &optional Parameter is optional. The parameter can be given as a two item list, where the first element is parameter name and the second is the default value. The parameter can be also given as a single item, in which case the default value is \fBNone\fP\&. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (defn total\-value [value &optional [value\-added\-tax 10]] \&... (+ (/ (* value value\-added\-tax) 100) value)) => (total\-value 100) 110.0 => (total\-value 100 1) 101.0 .ft P .fi .UNINDENT .UNINDENT .UNINDENT .sp &key .INDENT 0.0 .TP .B &kwargs Parameter will contain 0 or more keyword arguments. .sp The following code examples defines a function that will print all keyword arguments and their values. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (defn print\-parameters [&kwargs kwargs] \&... (for [(, k v) (.items kwargs)] (print k v))) => (apply print\-parameters [] {"parameter\-1" 1 "parameter\-2" 2}) parameter\-2 2 parameter\-1 1 .ft P .fi .UNINDENT .UNINDENT .TP .B &rest Parameter will contain 0 or more positional arguments. No other positional arguments may be specified after this one. .sp The following code example defines a function that can be given 0 to n numerical parameters. It then sums every odd number and subtracts every even number. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (defn zig\-zag\-sum [&rest numbers] (let [[odd\-numbers (list\-comp x [x numbers] (odd? x))] [even\-numbers (list\-comp x [x numbers] (even? x))]] (\- (sum odd\-numbers) (sum even\-numbers)))) => (zig\-zag\-sum) 0 => (zig\-zag\-sum 3 9 4) 8 => (zig\-zag\-sum 1 2 3 4 5 6) \-3 .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SS defn\-alias / defun\-alias .sp New in version 0.10.0. .sp The \fBdefn\-alias\fP and \fBdefun\-alias\fP macros are much like \fI\%defn\fP, with the distinction that instead of defining a function with a single name, these can also define aliases. Other than taking a list of symbols for function names as the first parameter, \fBdefn\-alias\fP and \fBdefun\-alias\fP are no different from \fBdefn\fP and \fBdefun\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn\-alias [main\-name alias] [] \&... (print "Hello!")) => (main\-name) "Hello!" => (alias) "Hello!" .ft P .fi .UNINDENT .UNINDENT .SS defmain .sp New in version 0.10.1. .sp The \fBdefmain\fP macro defines a main function that is immediately called with \fBsys.argv\fP as arguments if and only if this file is being executed as a script. In other words, this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmain [&rest args] (do\-something\-with args)) .ft P .fi .UNINDENT .UNINDENT .sp is the equivalent of: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def main(*args): do_something_with(args) return 0 if __name__ == "__main__": import sys retval = main(*sys.arg) if isinstance(retval, int): sys.exit(retval) .ft P .fi .UNINDENT .UNINDENT .sp Note that as you can see above, if you return an integer from this function, this will be used as the exit status for your script. (Python defaults to exit status 0 otherwise, which means everything\(aqs okay!) .sp (Since \fB(sys.exit 0)\fP is not run explicitly in the case of a non\-integer return from \fBdefmain\fP, it\(aqs a good idea to put \fB(defmain)\fP as the last piece of code in your file.) .SS defmacro .sp \fBdefmacro\fP is used to define macros. The general format is \fB(defmacro name [parameters] expr)\fP\&. .sp The following example defines a macro that can be used to swap order of elements in code, allowing the user to write code in infix notation, where operator is in between the operands. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defmacro infix [code] \&... (quasiquote ( \&... (unquote (get code 1)) \&... (unquote (get code 0)) \&... (unquote (get code 2))))) => (infix (1 + 1)) 2 .ft P .fi .UNINDENT .UNINDENT .SS defmacro\-alias .sp \fBdefmacro\-alias\fP is used to define macros with multiple names (aliases). The general format is \fB(defmacro\-alias [names] [parameters] expr)\fP\&. It creates multiple macros with the same parameter list and body, under the specified list of names. .sp The following example defines two macros, both of which allow the user to write code in infix notation. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defmacro\-alias [infix infi] [code] \&... (quasiquote ( \&... (unquote (get code 1)) \&... (unquote (get code 0)) \&... (unquote (get code 2))))) => (infix (1 + 1)) 2 => (infi (1 + 1)) 2 .ft P .fi .UNINDENT .UNINDENT .SS defmacro/g! .sp New in version 0.9.12. .sp \fBdefmacro/g!\fP is a special version of \fBdefmacro\fP that is used to automatically generate \fI\%gensym\fP for any symbol that starts with \fBg!\fP\&. .sp For example, \fBg!a\fP would become \fB(gensym "a")\fP\&. .sp \fBSEE ALSO:\fP .INDENT 0.0 .INDENT 3.5 Section using\-gensym .UNINDENT .UNINDENT .SS defreader .sp New in version 0.9.12. .sp \fBdefreader\fP defines a reader macro, enabling you to restructure or modify syntax. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defreader ^ [expr] (print expr)) => #^(1 2 3 4) (1 2 3 4) => #^"Hello" "Hello" .ft P .fi .UNINDENT .UNINDENT .sp \fBSEE ALSO:\fP .INDENT 0.0 .INDENT 3.5 Section Reader Macros .UNINDENT .UNINDENT .SS del .sp New in version 0.9.12. .sp \fBdel\fP removes an object from the current namespace. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv foo 42) => (del foo) => foo Traceback (most recent call last): File "", line 1, in NameError: name \(aqfoo\(aq is not defined .ft P .fi .UNINDENT .UNINDENT .sp \fBdel\fP can also remove objects from mappings, lists, and more. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv test (list (range 10))) => test [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] => (del (slice test 2 4)) ;; remove items from 2 to 4 excluded => test [0, 1, 4, 5, 6, 7, 8, 9] => (setv dic {"foo" "bar"}) => dic {"foo": "bar"} => (del (get dic "foo")) => dic {} .ft P .fi .UNINDENT .UNINDENT .SS doto .sp New in version 0.10.1. .sp \fBdoto\fP is used to simplify a sequence of method calls to an object. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (doto [] (.append 1) (.append 2) .reverse) [2 1] .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv collection []) => (.append collection 1) => (.append collection 2) => (.reverse collection) => collection [2 1] .ft P .fi .UNINDENT .UNINDENT .SS eval .sp \fBeval\fP evaluates a quoted expression and returns the value. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (eval \(aq(print "Hello World")) "Hello World" .ft P .fi .UNINDENT .UNINDENT .SS eval\-and\-compile .SS eval\-when\-compile .SS first / car .sp \fBfirst\fP and \fBcar\fP are macros for accessing the first element of a collection: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (first (range 10)) 0 .ft P .fi .UNINDENT .UNINDENT .SS for .sp \fBfor\fP is used to call a function for each element in a list or vector. The results of each call are discarded and the \fBfor\fP expression returns \fBNone\fP instead. The example code iterates over \fIcollection\fP and for each \fIelement\fP in \fIcollection\fP calls the \fBside\-effect\fP function with \fIelement\fP as its argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; assuming that (side\-effect) is a function that takes a single parameter (for [element collection] (side\-effect element)) ;; for can have an optional else block (for [element collection] (side\-effect element) (else (side\-effect\-2))) .ft P .fi .UNINDENT .UNINDENT .sp The optional \fBelse\fP block is only executed if the \fBfor\fP loop terminates normally. If the execution is halted with \fBbreak\fP, the \fBelse\fP block does not execute. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (for [element [1 2 3]] (if (< element 3) \&... (print element) \&... (break)) \&... (else (print "loop finished"))) 1 2 => (for [element [1 2 3]] (if (< element 4) \&... (print element) \&... (break)) \&... (else (print "loop finished"))) 1 2 3 loop finished .ft P .fi .UNINDENT .UNINDENT .SS genexpr .sp \fBgenexpr\fP is used to create generator expressions. It takes two or three parameters. The first parameter is the expression controlling the return value, while the second is used to select items from a list. The third and optional parameter can be used to filter out some of the items in the list based on a conditional expression. \fBgenexpr\fP is similar to \fBlist\-comp\fP, except it returns an iterable that evaluates values one by one instead of evaluating them immediately. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (def collection (range 10)) => (def filtered (genexpr x [x collection] (even? x))) => (list filtered) [0, 2, 4, 6, 8] .ft P .fi .UNINDENT .UNINDENT .SS gensym .sp New in version 0.9.12. .sp \fBgensym\fP is used to generate a unique symbol that allows macros to be written without accidental variable name clashes. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (gensym) u\(aq:G_1235\(aq => (gensym "x") u\(aq:x_1236\(aq .ft P .fi .UNINDENT .UNINDENT .sp \fBSEE ALSO:\fP .INDENT 0.0 .INDENT 3.5 Section using\-gensym .UNINDENT .UNINDENT .SS get .sp \fBget\fP is used to access single elements in lists and dictionaries. \fBget\fP takes two parameters: the \fIdata structure\fP and the \fIindex\fP or \fIkey\fP of the item. It will then return the corresponding value from the dictionary or the list. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (let [[animals {"dog" "bark" "cat" "meow"}] \&... [numbers ["zero" "one" "two" "three"]]] \&... (print (get animals "dog")) \&... (print (get numbers 2))) bark two .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBget\fP raises a KeyError if a dictionary is queried for a non\-existing key. .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBget\fP raises an IndexError if a list or a tuple is queried for an index that is out of bounds. .UNINDENT .UNINDENT .SS global .sp \fBglobal\fP can be used to mark a symbol as global. This allows the programmer to assign a value to a global symbol. Reading a global symbol does not require the \fBglobal\fP keyword \-\- only assigning it does. .sp The following example shows how the global symbol \fBa\fP is assigned a value in a function and is later on printed in another function. Without the \fBglobal\fP keyword, the second function would have thrown a \fBNameError\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn set\-a [value] (global a) (setv a value)) (defn print\-a [] (print a)) (set\-a 5) (print\-a) .ft P .fi .UNINDENT .UNINDENT .SS if / if\-not .sp New in version 0.10.0: if\-not .sp \fBif\fP is used to conditionally select code to be executed. It has to contain a condition block and the block to be executed if the condition block evaluates to \fBTrue\fP\&. Optionally, it may contain a final block that is executed in case the evaluation of the condition is \fBFalse\fP\&. .sp \fBif\-not\fP is similar, but the second block will be executed when the condition fails while the third and final block is executed when the test succeeds \-\- the opposite order of \fBif\fP\&. .sp Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (if (money\-left? account) (print "let\(aqs go shopping") (print "let\(aqs go and work")) (if\-not (money\-left? account) (print "let\(aqs go and work") (print "let\(aqs go shopping")) .ft P .fi .UNINDENT .UNINDENT .sp Python truthiness is respected. \fBNone\fP, \fBFalse\fP, zero of any numeric type, an empty sequence, and an empty dictionary are considered \fBFalse\fP; everything else is considered \fBTrue\fP\&. .SS lisp\-if / lif and lisp\-if\-not / lif\-not .sp New in version 0.10.0. .sp New in version 0.10.2: lisp\-if\-not / lif\-not .sp For those that prefer a more Lispy \fBif\fP clause, we have \fBlisp\-if\fP, or \fBlif\fP\&. This \fIonly\fP considers \fBNone\fP / \fBnil\fP to be false! All other "false\-ish" Python values are considered true. Conversely, we have \fBlisp\-if\-not\fP and \fBlif\-not\fP in parallel to \fBif\fP and \fBif\-not\fP which reverses the comparison. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (lisp\-if True "true" "false") "true" => (lisp\-if False "true" "false") "true" => (lisp\-if 0 "true" "false") "true" => (lisp\-if nil "true" "false") "false" => (lisp\-if None "true" "false") "false" => (lisp\-if\-not nil "true" "false") "true" => (lisp\-if\-not None "true" "false") "true" => (lisp\-if\-not False "true" "false") "false" ; Equivalent but shorter => (lif True "true" "false") "true" => (lif nil "true" "false") "false" => (lif\-not None "true" "false") "true" .ft P .fi .UNINDENT .UNINDENT .SS import .sp \fBimport\fP is used to import modules, like in Python. There are several ways that \fBimport\fP can be used. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; Imports each of these modules ;; ;; Python: ;; import sys ;; import os.path (import sys os.path) ;; Import from a module ;; ;; Python: from os.path import exists, isdir, isfile (import [os.path [exists isdir isfile]]) ;; Import with an alias ;; ;; Python: import sys as systest (import [sys :as systest]) ;; You can list as many imports as you like of different types. (import [tests.resources [kwtest function\-with\-a\-dash]] [os.path [exists isdir isfile]] [sys :as systest]) ;; Import all module functions into current namespace (import [sys [*]]) .ft P .fi .UNINDENT .UNINDENT .SS lambda / fn .sp \fBlambda\fP and \fBfn\fP can be used to define an anonymous function. The parameters are similar to \fBdefn\fP: the first parameter is vector of parameters and the rest is the body of the function. \fBlambda\fP returns a new function. In the following example, an anonymous function is defined and passed to another function for filtering output. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (def people [{:name "Alice" :age 20} \&... {:name "Bob" :age 25} \&... {:name "Charlie" :age 50} \&... {:name "Dave" :age 5}]) => (defn display\-people [people filter] \&... (for [person people] (if (filter person) (print (:name person))))) => (display\-people people (fn [person] (< (:age person) 25))) Alice Dave .ft P .fi .UNINDENT .UNINDENT .sp Just as in normal function definitions, if the first element of the body is a string, it serves as a docstring. This is useful for giving class methods docstrings. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv times\-three \&... (fn [x] \&... "Multiplies input by three and returns the result." \&... (* x 3))) .ft P .fi .UNINDENT .UNINDENT .sp This can be confirmed via Python\(aqs built\-in \fBhelp\fP function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (help times\-three) Help on function times_three: times_three(x) Multiplies input by three and returns result (END) .ft P .fi .UNINDENT .UNINDENT .SS last .sp New in version 0.10.2. .sp \fBlast\fP can be used for accessing the last element of a collection: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (last [2 4 6]) 6 .ft P .fi .UNINDENT .UNINDENT .SS let .sp \fBlet\fP is used to create lexically scoped variables. They are created at the beginning of the \fBlet\fP form and cease to exist after the form. The following example showcases this behaviour: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (let [[x 5]] (print x) \&... (let [[x 6]] (print x)) \&... (print x)) 5 6 5 .ft P .fi .UNINDENT .UNINDENT .sp The \fBlet\fP macro takes two parameters: a vector defining \fIvariables\fP and the \fIbody\fP which gets executed. \fIvariables\fP is a vector where each element is either a single variable or a vector defining a variable value pair. In the case of a single variable, it is assigned value \fBNone\fP; otherwise, the supplied value is used. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (let [x [y 5]] (print x y)) None 5 .ft P .fi .UNINDENT .UNINDENT .SS list\-comp .sp \fBlist\-comp\fP performs list comprehensions. It takes two or three parameters. The first parameter is the expression controlling the return value, while the second is used to select items from a list. The third and optional parameter can be used to filter out some of the items in the list based on a conditional expression. Some examples: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (def collection (range 10)) => (list\-comp x [x collection]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] => (list\-comp (* x 2) [x collection]) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] => (list\-comp (* x 2) [x collection] (< x 5)) [0, 2, 4, 6, 8] .ft P .fi .UNINDENT .UNINDENT .SS not .sp \fBnot\fP is used in logical expressions. It takes a single parameter and returns a reversed truth value. If \fBTrue\fP is given as a parameter, \fBFalse\fP will be returned, and vice\-versa. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (not True) False => (not False) True => (not None) True .ft P .fi .UNINDENT .UNINDENT .SS or .sp \fBor\fP is used in logical expressions. It takes at least two parameters. It will return the first non\-false parameter. If no such value exists, the last parameter will be returned. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (or True False) True => (and False False) False => (and False 1 True False) 1 .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBor\fP short\-circuits and stops evaluating parameters as soon as the first true value is encountered. .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (or True (print "hello")) True .ft P .fi .UNINDENT .UNINDENT .SS print .sp \fBprint\fP is used to output on screen. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "Hello world!") .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBprint\fP always returns \fBNone\fP\&. .UNINDENT .UNINDENT .SS quasiquote .sp \fBquasiquote\fP allows you to quote a form, but also selectively evaluate expressions. Expressions inside a \fBquasiquote\fP can be selectively evaluated using \fBunquote\fP (\fB~\fP). The evaluated form can also be spliced using \fBunquote\-splice\fP (\fB~@\fP). Quasiquote can be also written using the backquote (\fB\(ga\fP) symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; let \(gaqux\(aq be a variable with value (bar baz) \(ga(foo ~qux) ; equivalent to \(aq(foo (bar baz)) \(ga(foo ~@qux) ; equivalent to \(aq(foo bar baz) .ft P .fi .UNINDENT .UNINDENT .SS quote .sp \fBquote\fP returns the form passed to it without evaluating it. \fBquote\fP can alternatively be written using the apostrophe (\fB\(aq\fP) symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv x \(aq(print "Hello World")) ; variable x is set to expression & not evaluated => x (u\(aqprint\(aq u\(aqHello World\(aq) => (eval x) Hello World .ft P .fi .UNINDENT .UNINDENT .SS require .sp \fBrequire\fP is used to import macros from a given module. It takes at least one parameter specifying the module which macros should be imported. Multiple modules can be imported with a single \fBrequire\fP\&. .sp The following example will import macros from \fBmodule\-1\fP and \fBmodule\-2\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require module\-1 module\-2) .ft P .fi .UNINDENT .UNINDENT .SS rest / cdr .sp \fBrest\fP and \fBcdr\fP return the collection passed as an argument without the first element: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (rest (range 10)) [1, 2, 3, 4, 5, 6, 7, 8, 9] .ft P .fi .UNINDENT .UNINDENT .SS set\-comp .sp \fBset\-comp\fP is used to create sets. It takes two or three parameters. The first parameter is for controlling the return value, while the second is used to select items from a sequence. The third and optional parameter can be used to filter out some of the items in the sequence based on a conditional expression. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv data [1 2 3 4 5 2 3 4 5 3 4 5]) => (set\-comp x [x data] (odd? x)) {1, 3, 5} .ft P .fi .UNINDENT .UNINDENT .SS slice .sp \fBslice\fP can be used to take a subset of a list and create a new list from it. The form takes at least one parameter specifying the list to slice. Two optional parameters can be used to give the start and end position of the subset. If they are not supplied, the default value of \fBNone\fP will be used instead. The third optional parameter is used to control step between the elements. .sp \fBslice\fP follows the same rules as its Python counterpart. Negative indices are counted starting from the end of the list. Some example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (def collection (range 10)) => (slice collection) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] => (slice collection 5) [5, 6, 7, 8, 9] => (slice collection 2 8) [2, 3, 4, 5, 6, 7] => (slice collection 2 8 2) [2, 4, 6] => (slice collection \-4 \-2) [6, 7] .ft P .fi .UNINDENT .UNINDENT .SS throw / raise .sp The \fBthrow\fP or \fBraise\fP forms can be used to raise an \fBException\fP at runtime. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (throw) ; re\-rase the last exception (throw IOError) ; Throw an IOError (throw (IOError "foobar")) ; Throw an IOError("foobar") .ft P .fi .UNINDENT .UNINDENT .sp \fBthrow\fP can accept a single argument (an \fBException\fP class or instance) or no arguments to re\-raise the last \fBException\fP\&. .SS try .sp The \fBtry\fP form is used to start a \fBtry\fP / \fBcatch\fP block. The form is used as follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (try (error\-prone\-function) (catch [e ZeroDivisionError] (print "Division by zero")) (else (print "no errors")) (finally (print "all done"))) .ft P .fi .UNINDENT .UNINDENT .sp \fBtry\fP must contain at least one \fBcatch\fP block, and may optionally include an \fBelse\fP or \fBfinally\fP block. If an error is raised with a matching catch block during the execution of \fBerror\-prone\-function\fP, that \fBcatch\fP block will be executed. If no errors are raised, the \fBelse\fP block is executed. The \fBfinally\fP block will be executed last regardless of whether or not an error was raised. .SS unless .sp The \fBunless\fP macro is a shorthand for writing an \fBif\fP statement that checks if the given conditional is \fBFalse\fP\&. The following shows the expansion of this macro. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (unless conditional statement) (if conditional None (do statement)) .ft P .fi .UNINDENT .UNINDENT .SS unquote .sp Within a quasiquoted form, \fBunquote\fP forces evaluation of a symbol. \fBunquote\fP is aliased to the tilde (\fB~\fP) symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (def name "Cuddles") (quasiquote (= name (unquote name))) ;=> (u\(aq=\(aq u\(aqname\(aq u\(aqCuddles\(aq) \(ga(= name ~name) ;=> (u\(aq=\(aq u\(aqname\(aq u\(aqCuddles\(aq) .ft P .fi .UNINDENT .UNINDENT .SS unquote\-splice .sp \fBunquote\-splice\fP forces the evaluation of a symbol within a quasiquoted form, much like \fBunquote\fP\&. \fBunquote\-splice\fP can only be used when the symbol being unquoted contains an iterable value, as it "splices" that iterable into the quasiquoted form. \fBunquote\-splice\fP is aliased to the \fB~@\fP symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (def nums [1 2 3 4]) (quasiquote (+ (unquote\-splice nums))) ;=> (u\(aq+\(aq 1L 2L 3L 4L) \(ga(+ ~@nums) ;=> (u\(aq+\(aq 1L 2L 3L 4L) .ft P .fi .UNINDENT .UNINDENT .SS when .sp \fBwhen\fP is similar to \fBunless\fP, except it tests when the given conditional is \fBTrue\fP\&. It is not possible to have an \fBelse\fP block in a \fBwhen\fP macro. The following shows the expansion of the macro. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (when conditional statement) (if conditional (do statement)) .ft P .fi .UNINDENT .UNINDENT .SS while .sp \fBwhile\fP is used to execute one or more blocks as long as a condition is met. The following example will output "Hello world!" to the screen indefinitely: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (while True (print "Hello world!")) .ft P .fi .UNINDENT .UNINDENT .SS with .sp \fBwith\fP is used to wrap the execution of a block within a context manager. The context manager can then set up the local system and tear it down in a controlled manner. The archetypical example of using \fBwith\fP is when processing files. \fBwith\fP can bind context to an argument or ignore it completely, as shown below: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with [[arg (expr)]] block) (with [[(expr)]] block) (with [[arg (expr)] [(expr)]] block) .ft P .fi .UNINDENT .UNINDENT .sp The following example will open the \fBNEWS\fP file and print its content to the screen. The file is automatically closed after it has been processed. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with [[f (open "NEWS")]] (print (.read f))) .ft P .fi .UNINDENT .UNINDENT .SS with\-decorator .sp \fBwith\-decorator\fP is used to wrap a function with another. The function performing the decoration should accept a single value: the function being decorated, and return a new function. \fBwith\-decorator\fP takes a minimum of two parameters: the function performing decoration and the function being decorated. More than one decorator function can be applied; they will be applied in order from outermost to innermost, ie. the first decorator will be the outermost one, and so on. Decorators with arguments are called just like a function call. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with\-decorator decorator\-fun (defn some\-function [] ...) (with\-decorator decorator1 decorator2 ... (defn some\-function [] ...) (with\-decorator (decorator arg) .. (defn some\-function [] ...) .ft P .fi .UNINDENT .UNINDENT .sp In the following example, \fBinc\-decorator\fP is used to decorate the function \fBaddition\fP with a function that takes two parameters and calls the decorated function with values that are incremented by 1. When the decorated \fBaddition\fP is called with values 1 and 1, the end result will be 4 (\fB1+1 + 1+1\fP). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn inc\-decorator [func] \&... (fn [value\-1 value\-2] (func (+ value\-1 1) (+ value\-2 1)))) => (defn inc2\-decorator [func] \&... (fn [value\-1 value\-2] (func (+ value\-1 2) (+ value\-2 2)))) => (with\-decorator inc\-decorator (defn addition [a b] (+ a b))) => (addition 1 1) 4 => (with\-decorator inc2\-decorator inc\-decorator \&... (defn addition [a b] (+ a b))) => (addition 1 1) 8 .ft P .fi .UNINDENT .UNINDENT .SS with\-gensyms .sp New in version 0.9.12. .sp \fBwith\-gensym\fP is used to generate a set of \fI\%gensym\fP for use in a macro. The following code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with\-gensyms [a b c] ...) .ft P .fi .UNINDENT .UNINDENT .sp expands to: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (let [[a (gensym) [b (gensym) [c (gensym)]] ...) .ft P .fi .UNINDENT .UNINDENT .sp \fBSEE ALSO:\fP .INDENT 0.0 .INDENT 3.5 Section using\-gensym .UNINDENT .UNINDENT .SS yield .sp \fByield\fP is used to create a generator object that returns one or more values. The generator is iterable and therefore can be used in loops, list comprehensions and other similar constructs. .sp The function \fBrandom\-numbers\fP shows how generators can be used to generate infinite series without consuming infinite amount of memory. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn multiply [bases coefficients] \&... (for [[(, base coefficient) (zip bases coefficients)]] \&... (yield (* base coefficient)))) => (multiply (range 5) (range 5)) => (list\-comp value [value (multiply (range 10) (range 10))]) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] => (import random) => (defn random\-numbers [low high] \&... (while True (yield (.randint random low high)))) => (list\-comp x [x (take 15 (random\-numbers 1 50))])]) [7, 41, 6, 22, 32, 17, 5, 38, 18, 38, 17, 14, 23, 23, 19] .ft P .fi .UNINDENT .UNINDENT .SS yield\-from .sp New in version 0.9.13. .sp \fBPYTHON 3.3 AND UP ONLY!\fP .sp \fByield\-from\fP is used to call a subgenerator. This is useful if you want your coroutine to be able to delegate its processes to another coroutine, say, if using something fancy like \fI\%asyncio\fP\&. .SS Hy Core .SS Core Functions .SS butlast .sp Usage: \fB(butlast coll)\fP .sp Returns an iterator of all but the last item in \fIcoll\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (butlast (range 10))) [0, 1, 2, 3, 4, 5, 6, 7, 8] => (list (butlast [1])) [] => (list (butlast [])) [] => (import itertools) => (list (take 5 (butlast (itertools.count 10)))) [10, 11, 12, 13, 14] .ft P .fi .UNINDENT .UNINDENT .SS coll? .sp New in version 0.10.0. .sp Usage: \fB(coll? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is iterable and not a string. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (coll? [1 2 3 4]) True => (coll? {"a" 1 "b" 2}) True => (coll? "abc") False .ft P .fi .UNINDENT .UNINDENT .SS cons .sp New in version 0.10.0. .sp Usage: \fB(cons a b)\fP .sp Returns a fresh cons cell with car \fIa\fP and cdr \fIb\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv a (cons \(aqhd \(aqtl)) => (= \(aqhd (car a)) True => (= \(aqtl (cdr a)) True .ft P .fi .UNINDENT .UNINDENT .SS cons? .sp New in version 0.10.0. .sp Usage: \fB(cons? foo)\fP .sp Checks whether \fIfoo\fP is a cons cell\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv a (cons \(aqhd \(aqtl)) => (cons? a) True => (cons? nil) False => (cons? [1 2 3]) False .ft P .fi .UNINDENT .UNINDENT .SS dec .sp Usage: \fB(dec x)\fP .sp Returns one less than \fIx\fP\&. Equivalent to \fB(\- x 1)\fP\&. Raises \fBTypeError\fP if \fB(not (numeric? x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (dec 3) 2 => (dec 0) \-1 => (dec 12.3) 11.3 .ft P .fi .UNINDENT .UNINDENT .SS disassemble .sp New in version 0.10.0. .sp Usage: \fB(disassemble tree &optional [codegen false])\fP .sp Dump the Python AST for given Hy \fItree\fP to standard output. If \fIcodegen\fP is \fBTrue\fP, the function prints Python code instead. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (disassemble \(aq(print "Hello World!")) Module( body=[ Expr(value=Call(func=Name(id=\(aqprint\(aq), args=[Str(s=\(aqHello World!\(aq)], keywords=[], starargs=None, kwargs=None))]) => (disassemble \(aq(print "Hello World!") true) print(\(aqHello World!\(aq) .ft P .fi .UNINDENT .UNINDENT .SS empty? .sp Usage: \fB(empty? coll)\fP .sp Returns \fBTrue\fP if \fIcoll\fP is empty. Equivalent to \fB(= 0 (len coll))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (empty? []) True => (empty? "") True => (empty? (, 1 2)) False .ft P .fi .UNINDENT .UNINDENT .SS every? .sp New in version 0.10.0. .sp Usage: \fB(every? pred coll)\fP .sp Returns \fBTrue\fP if \fB(pred x)\fP is logical true for every \fIx\fP in \fIcoll\fP, otherwise \fBFalse\fP\&. Return \fBTrue\fP if \fIcoll\fP is empty. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (every? even? [2 4 6]) True => (every? even? [1 3 5]) False => (every? even? [2 4 5]) False => (every? even? []) True .ft P .fi .UNINDENT .UNINDENT .SS float? .sp Usage: \fB(float? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a float. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (float? 3.2) True => (float? \-2) False .ft P .fi .UNINDENT .UNINDENT .SS even? .sp Usage: \fB(even? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is even. Raises \fBTypeError\fP if \fB(not (numeric? x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (even? 2) True => (even? 13) False => (even? 0) True .ft P .fi .UNINDENT .UNINDENT .SS identity .sp Usage: \fB(identity x)\fP .sp Returns the argument supplied to the function. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (identity 4) 4 => (list (map identity [1 2 3 4])) [1 2 3 4] .ft P .fi .UNINDENT .UNINDENT .SS inc .sp Usage: \fB(inc x)\fP .sp Returns one more than \fIx\fP\&. Equivalent to \fB(+ x 1)\fP\&. Raises \fBTypeError\fP if \fB(not (numeric? x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (inc 3) 4 => (inc 0) 1 => (inc 12.3) 13.3 .ft P .fi .UNINDENT .UNINDENT .SS instance? .sp Usage: \fB(instance? class x)\fP .sp Returns \fBTrue\fP if \fIx\fP is an instance of \fIclass\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (instance? float 1.0) True => (instance? int 7) True => (instance? str (str "foo")) True => (defclass TestClass [object]) => (setv inst (TestClass)) => (instance? TestClass inst) True .ft P .fi .UNINDENT .UNINDENT .SS integer? .sp Usage: \fB(integer? x)\fP .sp Returns \fITrue\fP if \fIx\fP is an integer. For Python 2, this is either \fBint\fP or \fBlong\fP\&. For Python 3, this is \fBint\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (integer? 3) True => (integer? \-2.4) False .ft P .fi .UNINDENT .UNINDENT .SS interleave .sp New in version 0.10.1. .sp Usage: \fB(interleave seq1 seq2 ...)\fP .sp Returns an iterable of the first item in each of the sequences, then the second, etc. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (interleave (range 5) (range 100 105))) [0, 100, 1, 101, 2, 102, 3, 103, 4, 104] => (list (interleave (range 1000000) "abc")) [0, \(aqa\(aq, 1, \(aqb\(aq, 2, \(aqc\(aq] .ft P .fi .UNINDENT .UNINDENT .SS interpose .sp New in version 0.10.1. .sp Usage: \fB(interpose item seq)\fP .sp Returns an iterable of the elements of the sequence separated by the item. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (interpose "!" "abcd")) [\(aqa\(aq, \(aq!\(aq, \(aqb\(aq, \(aq!\(aq, \(aqc\(aq, \(aq!\(aq, \(aqd\(aq] => (list (interpose \-1 (range 5))) [0, \-1, 1, \-1, 2, \-1, 3, \-1, 4] .ft P .fi .UNINDENT .UNINDENT .SS iterable? .sp Usage: \fB(iterable? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is iterable. Iterable objects return a new iterator when \fB(iter x)\fP is called. Contrast with \fI\%iterator?\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => ;; works for strings => (iterable? (str "abcde")) True => ;; works for lists => (iterable? [1 2 3 4 5]) True => ;; works for tuples => (iterable? (, 1 2 3)) True => ;; works for dicts => (iterable? {:a 1 :b 2 :c 3}) True => ;; works for iterators/generators => (iterable? (repeat 3)) True .ft P .fi .UNINDENT .UNINDENT .SS iterator? .sp Usage: \fB(iterator? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is an iterator. Iterators are objects that return themselves as an iterator when \fB(iter x)\fP is called. Contrast with \fI\%iterable?\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => ;; doesn\(aqt work for a list => (iterator? [1 2 3 4 5]) False => ;; but we can get an iter from the list => (iterator? (iter [1 2 3 4 5])) True => ;; doesn\(aqt work for dict => (iterator? {:a 1 :b 2 :c 3}) False => ;; create an iterator from the dict => (iterator? (iter {:a 1 :b 2 :c 3})) True .ft P .fi .UNINDENT .UNINDENT .SS list* .sp Usage: \fB(list* head &rest tail)\fP .sp Generates a chain of nested cons cells (a dotted list) containing the arguments. If the argument list only has one element, return it. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list* 1 2 3 4) (1 2 3 . 4) => (list* 1 2 3 [4]) [1, 2, 3, 4] => (list* 1) 1 => (cons? (list* 1 2 3 4)) True .ft P .fi .UNINDENT .UNINDENT .SS macroexpand .sp New in version 0.10.0. .sp Usage: \fB(macroexpand form)\fP .sp Returns the full macro expansion of \fIform\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (macroexpand \(aq(\-> (a b) (x y))) (u\(aqx\(aq (u\(aqa\(aq u\(aqb\(aq) u\(aqy\(aq) => (macroexpand \(aq(\-> (a b) (\-> (c d) (e f)))) (u\(aqe\(aq (u\(aqc\(aq (u\(aqa\(aq u\(aqb\(aq) u\(aqd\(aq) u\(aqf\(aq) .ft P .fi .UNINDENT .UNINDENT .SS macroexpand\-1 .sp New in version 0.10.0. .sp Usage: \fB(macroexpand\-1 form)\fP .sp Returns the single step macro expansion of \fIform\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (macroexpand\-1 \(aq(\-> (a b) (\-> (c d) (e f)))) (u\(aq_>\(aq (u\(aqa\(aq u\(aqb\(aq) (u\(aqc\(aq u\(aqd\(aq) (u\(aqe\(aq u\(aqf\(aq)) .ft P .fi .UNINDENT .UNINDENT .SS merge\-with .sp New in version 0.10.1. .sp Usage: \fB(merge\-with f &rest maps)\fP .sp Returns a map that consist of the rest of the maps joined onto first. If a key occurs in more than one map, the mapping(s) from the latter (left\-to\-right) will be combined with the mapping in the result by calling \fB(f val\-in\-result val\-in\-latter)\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (merge\-with (fn [x y] (+ x y)) {"a" 10 "b" 20} {"a" 1 "c" 30}) {u\(aqa\(aq: 11L, u\(aqc\(aq: 30L, u\(aqb\(aq: 20L} .ft P .fi .UNINDENT .UNINDENT .SS neg? .sp Usage: \fB(neg? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is less than zero. Raises \fBTypeError\fP if \fB(not (numeric? x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (neg? \-2) True => (neg? 3) False => (neg? 0) False .ft P .fi .UNINDENT .UNINDENT .SS nil? .sp Usage: \fB(nil? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is \fBnil\fP / \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (nil? nil) True => (nil? None) True => (nil? 0) False => (setf x nil) => (nil? x) True => ;; list.append always returns None => (nil? (.append [1 2 3] 4)) True .ft P .fi .UNINDENT .UNINDENT .SS none? .sp Usage: \fB(none? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (none? None) True => (none? 0) False => (setf x None) => (none? x) True => ;; list.append always returns None => (none? (.append [1 2 3] 4)) True .ft P .fi .UNINDENT .UNINDENT .SS nth .sp Usage: \fB(nth coll n &optional [default nil])\fP .sp Returns the \fIn\fP\-th item in a collection, counting from 0. Return the default value, \fBnil\fP, if out of bounds (unless specified otherwise). Raises \fBValueError\fP if \fIn\fP is negative. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (nth [1 2 4 7] 1) 2 => (nth [1 2 4 7] 3) 7 => (nil? (nth [1 2 4 7] 5)) True => (nth [1 2 4 7] 5 "default") \(aqdefault\(aq => (nth (take 3 (drop 2 [1 2 3 4 5 6])) 2)) 5 => (nth [1 2 4 7] \-1) Traceback (most recent call last): ... ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize. .ft P .fi .UNINDENT .UNINDENT .SS numeric? .sp Usage: \fB(numeric? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a numeric, as defined in Python\(aqs \fBnumbers.Number\fP class. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (numeric? \-2) True => (numeric? 3.2) True => (numeric? "foo") False .ft P .fi .UNINDENT .UNINDENT .SS odd? .sp Usage: \fB(odd? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is odd. Raises \fBTypeError\fP if \fB(not (numeric? x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (odd? 13) True => (odd? 2) False => (odd? 0) False .ft P .fi .UNINDENT .UNINDENT .SS pos? .sp Usage: \fB(pos? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is greater than zero. Raises \fBTypeError\fP if \fB(not (numeric? x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (pos? 3) True => (pos? \-2) False => (pos? 0) False .ft P .fi .UNINDENT .UNINDENT .SS second .sp Usage: \fB(second coll)\fP .sp Returns the second member of \fIcoll\fP\&. Equivalent to \fB(get coll 1)\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (second [0 1 2]) 1 .ft P .fi .UNINDENT .UNINDENT .SS some .sp New in version 0.10.0. .sp Usage: \fB(some pred coll)\fP .sp Returns the first logically\-true value of \fB(pred x)\fP for any \fBx\fP in \fIcoll\fP, otherwise \fBnil\fP\&. Return \fBnil\fP if \fIcoll\fP is empty. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (some even? [2 4 6]) True => (nil? (some even? [1 3 5])) True => (nil? (some identity [0 "" []])) True => (some identity [0 "non\-empty\-string" []]) \(aqnon\-empty\-string\(aq => (nil? (some even? [])) True .ft P .fi .UNINDENT .UNINDENT .SS string? .sp Usage: \fB(string? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a string. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (string? "foo") True => (string? \-2) False .ft P .fi .UNINDENT .UNINDENT .SS symbol? .sp Usage: \fB(symbol? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (symbol? \(aqfoo) True => (symbol? \(aq[a b c]) False .ft P .fi .UNINDENT .UNINDENT .SS zero? .sp Usage: \fB(zero? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is zero. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (zero? 3) False => (zero? \-2) False => (zero? 0) True .ft P .fi .UNINDENT .UNINDENT .SS Sequence Functions .sp Sequence functions can either create or operate on a potentially infinite sequence without requiring the sequence be fully realized in a list or similar container. They do this by returning a Python iterator. .sp We can use the canonical infinite Fibonacci number generator as an example of how to use some of these functions. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn fib [] (setv a 0) (setv b 1) (while true (yield a) (setv (, a b) (, b (+ a b))))) .ft P .fi .UNINDENT .UNINDENT .sp Note the \fB(while true ...)\fP loop. If we run this in the REPL, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (fib) .ft P .fi .UNINDENT .UNINDENT .sp Calling the function only returns an iterator, but does no work until we consume it. Trying something like this is not recommend as the infinite loop will run until it consumes all available RAM, or in this case until I killed it. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (fib)) [1] 91474 killed hy .ft P .fi .UNINDENT .UNINDENT .sp To get the first 10 Fibonacci numbers, use \fI\%take\fP\&. Note that \fI\%take\fP also returns a generator, so I create a list from it. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take 10 (fib))) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] .ft P .fi .UNINDENT .UNINDENT .sp To get the Fibonacci number at index 9, (starting from 0): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (nth (fib) 9) 34 .ft P .fi .UNINDENT .UNINDENT .SS cycle .sp Usage: \fB(cycle coll)\fP .sp Returns an infinite iterator of the members of coll. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take 7 (cycle [1 2 3]))) [1, 2, 3, 1, 2, 3, 1] => (list (take 2 (cycle [1 2 3]))) [1, 2] .ft P .fi .UNINDENT .UNINDENT .SS distinct .sp Usage: \fB(distinct coll)\fP .sp Returns an iterator containing only the unique members in \fIcoll\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (distinct [ 1 2 3 4 3 5 2 ])) [1, 2, 3, 4, 5] => (list (distinct [])) [] => (list (distinct (iter [ 1 2 3 4 3 5 2 ]))) [1, 2, 3, 4, 5] .ft P .fi .UNINDENT .UNINDENT .SS drop .sp Usage: \fB(drop n coll)\fP .sp Returns an iterator, skipping the first \fIn\fP members of \fIcoll\fP\&. Raises \fBValueError\fP if \fIn\fP is negative. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (drop 2 [1 2 3 4 5])) [3, 4, 5] => (list (drop 4 [1 2 3 4 5])) [5] => (list (drop 0 [1 2 3 4 5])) [1, 2, 3, 4, 5] => (list (drop 6 [1 2 3 4 5])) [] .ft P .fi .UNINDENT .UNINDENT .SS drop\-last .sp Usage: \fB(drop\-last n coll)\fP .sp Returns an iterator of all but the last \fIn\fP items in \fIcoll\fP\&. Raises \fBValueError\fP if \fIn\fP is negative. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (drop\-last 5 (range 10 20))) [10, 11, 12, 13, 14] => (list (drop\-last 0 (range 5))) [0, 1, 2, 3, 4] => (list (drop\-last 100 (range 100))) [] => (import itertools) => (list (take 5 (drop\-last 100 (itertools.count 10)))) [10, 11, 12, 13, 14] .ft P .fi .UNINDENT .UNINDENT .SS drop\-while .sp Usage: \fB(drop\-while pred coll)\fP .sp Returns an iterator, skipping members of \fIcoll\fP until \fIpred\fP is \fBFalse\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (drop\-while even? [2 4 7 8 9])) [7, 8, 9] => (list (drop\-while numeric? [1 2 3 None "a"]))) [None, u\(aqa\(aq] => (list (drop\-while pos? [2 4 7 8 9])) [] .ft P .fi .UNINDENT .UNINDENT .SS filter .sp Usage: \fB(filter pred coll)\fP .sp Returns an iterator for all items in \fIcoll\fP that pass the predicate \fIpred\fP\&. .sp See also \fI\%remove\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (filter pos? [1 2 3 \-4 5 \-7])) [1, 2, 3, 5] => (list (filter even? [1 2 3 \-4 5 \-7])) [2, \-4] .ft P .fi .UNINDENT .UNINDENT .SS flatten .sp New in version 0.9.12. .sp Usage: \fB(flatten coll)\fP .sp Returns a single list of all the items in \fIcoll\fP, by flattening all contained lists and/or tuples. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (flatten [1 2 [3 4] 5]) [1, 2, 3, 4, 5] => (flatten ["foo" (, 1 2) [1 [2 3] 4] "bar"]) [\(aqfoo\(aq, 1, 2, 1, 2, 3, 4, \(aqbar\(aq] .ft P .fi .UNINDENT .UNINDENT .SS iterate .sp Usage: \fB(iterate fn x)\fP .sp Returns an iterator of \fIx\fP, \fIfn(x)\fP, \fIfn(fn(x))\fP, etc. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take 5 (iterate inc 5))) [5, 6, 7, 8, 9] => (list (take 5 (iterate (fn [x] (* x x)) 5))) [5, 25, 625, 390625, 152587890625] .ft P .fi .UNINDENT .UNINDENT .SS read .sp Usage: \fB(read &optional [from\-file eof])\fP .sp Reads the next Hy expression from \fIfrom\-file\fP (defaulting to \fBsys.stdin\fP), and can take a single byte as EOF (defaults to an empty string). Raises \fBEOFError\fP if \fIfrom\-file\fP ends before a complete expression can be parsed. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (read) (+ 2 2) (\(aq+\(aq 2 2) => (eval (read)) (+ 2 2) 4 => (import io) => (def buffer (io.StringIO "(+ 2 2)\en(\- 2 1)")) => (eval (apply read [] {"from_file" buffer})) 4 => (eval (apply read [] {"from_file" buffer})) 1 => ; assuming "example.hy" contains: => ; (print "hello") => ; (print "hyfriends!") => (with [[f (open "example.hy")]] \&... (try \&... (while true \&... (let [[exp (read f)]] \&... (do \&... (print "OHY" exp) \&... (eval exp)))) \&... (catch [e EOFError] \&... (print "EOF!")))) OHY (\(aqprint\(aq \(aqhello\(aq) hello OHY (\(aqprint\(aq \(aqhyfriends!\(aq) hyfriends! EOF! .ft P .fi .UNINDENT .UNINDENT .SS remove .sp Usage: \fB(remove pred coll)\fP .sp Returns an iterator from \fIcoll\fP with elements that pass the predicate, \fIpred\fP, removed. .sp See also \fI\%filter\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (remove odd? [1 2 3 4 5 6 7])) [2, 4, 6] => (list (remove pos? [1 2 3 4 5 6 7])) [] => (list (remove neg? [1 2 3 4 5 6 7])) [1, 2, 3, 4, 5, 6, 7] .ft P .fi .UNINDENT .UNINDENT .SS repeat .sp Usage: \fB(repeat x)\fP .sp Returns an iterator (infinite) of \fBx\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take 6 (repeat "s"))) [u\(aqs\(aq, u\(aqs\(aq, u\(aqs\(aq, u\(aqs\(aq, u\(aqs\(aq, u\(aqs\(aq] .ft P .fi .UNINDENT .UNINDENT .SS repeatedly .sp Usage: \fB(repeatedly fn)\fP .sp Returns an iterator by calling \fIfn\fP repeatedly. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import [random [randint]]) => (list (take 5 (repeatedly (fn [] (randint 0 10))))) [6, 2, 0, 6, 7] .ft P .fi .UNINDENT .UNINDENT .SS take .sp Usage: \fB(take n coll)\fP .sp Returns an iterator containing the first \fIn\fP members of \fIcoll\fP\&. Raises \fBValueError\fP if \fIn\fP is negative. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take 3 [1 2 3 4 5])) [1, 2, 3] => (list (take 4 (repeat "s"))) [u\(aqs\(aq, u\(aqs\(aq, u\(aqs\(aq, u\(aqs\(aq] => (list (take 0 (repeat "s"))) [] .ft P .fi .UNINDENT .UNINDENT .SS take\-nth .sp Usage: \fB(take\-nth n coll)\fP .sp Returns an iterator containing every \fIn\fP\-th member of \fIcoll\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take\-nth 2 [1 2 3 4 5 6 7])) [1, 3, 5, 7] => (list (take\-nth 3 [1 2 3 4 5 6 7])) [1, 4, 7] => (list (take\-nth 4 [1 2 3 4 5 6 7])) [1, 5] => (list (take\-nth 10 [1 2 3 4 5 6 7])) [1] .ft P .fi .UNINDENT .UNINDENT .SS take\-while .sp Usage: \fB(take\-while pred coll)\fP .sp Returns an iterator from \fIcoll\fP as long as \fIpred\fP returns \fBTrue\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (take\-while pos? [ 1 2 3 \-4 5])) [1, 2, 3] => (list (take\-while neg? [ \-4 \-3 1 2 5])) [\-4, \-3] => (list (take\-while neg? [ 1 2 3 \-4 5])) [] .ft P .fi .UNINDENT .UNINDENT .SS zipwith .sp New in version 0.9.13. .sp Usage: \fB(zipwith fn coll ...)\fP .sp Equivalent to \fBzip\fP, but uses a multi\-argument function instead of creating a tuple. If \fBzipwith\fP is called with N collections, then \fIfn\fP must accept N arguments. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import operator) => (list (zipwith operator.add [1 2 3] [4 5 6])) [5, 7, 9] .ft P .fi .UNINDENT .UNINDENT .SS Reader Macros .sp Reader macros gives Lisp the power to modify and alter syntax on the fly. You don\(aqt want Polish notation? A reader macro can easily do just that. Want Clojure\(aqs way of having a regex? Reader macros can also do this easily. .SS Syntax .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defreader ^ [expr] (print expr)) => #^(1 2 3 4) (1 2 3 4) => #^"Hello" "Hello" => #^1+2+3+4+3+2 1+2+3+4+3+2 .ft P .fi .UNINDENT .UNINDENT .sp Hy has no literal for tuples. Lets say you dislike \fI(, ...)\fP and want something else. This is a problem reader macros are able to solve in a neat way. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defreader t [expr] \(ga(, ~@expr)) => #t(1 2 3) (1, 2, 3) .ft P .fi .UNINDENT .UNINDENT .sp You could even do it like Clojure and have a literal for regular expressions! .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import re) => (defreader r [expr] \(ga(re.compile ~expr)) => #r".*" <_sre.SRE_Pattern object at 0xcv7713ph15#> .ft P .fi .UNINDENT .UNINDENT .SS Implementation .sp \fBdefreader\fP takes a single character as symbol name for the reader macro; anything longer will return an error. Implementation\-wise, \fBdefreader\fP expands into a lambda covered with a decorator. This decorator saves the lambda in a dictionary with its module name and symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defreader ^ [expr] (print expr)) ;=> (with_decorator (hy.macros.reader ^) (fn [expr] (print expr))) .ft P .fi .UNINDENT .UNINDENT .sp \fB#\fP expands into \fB(dispatch_reader_macro ...)\fP where the symbol and expression is passed to the correct function. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => #^() ;=> (dispatch_reader_macro ^ ()) => #^"Hello" "Hello" .ft P .fi .UNINDENT .UNINDENT .sp \fBWARNING:\fP .INDENT 0.0 .INDENT 3.5 Because of a limitation in Hy\(aqs lexer and parser, reader macros can\(aqt redefine defined syntax such as \fB()[]{}\fP\&. This will most likely be addressed in the future. .UNINDENT .UNINDENT .SS Internal Hy Documentation .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 These bits are mostly useful for folks who hack on Hy itself, but can also be used for those delving deeper in macro programming. .UNINDENT .UNINDENT .SS Hy Models .SS Introduction to Hy Models .sp Hy models are a very thin layer on top of regular Python objects, representing Hy source code as data. Models only add source position information, and a handful of methods to support clean manipulation of Hy source code, for instance in macros. To achieve that goal, Hy models are mixins of a base Python class and \fI\%HyObject\fP\&. .SS HyObject .sp \fBhy.models.HyObject\fP is the base class of Hy models. It only implements one method, \fBreplace\fP, which replaces the source position of the current object with the one passed as argument. This allows us to keep track of the original position of expressions that get modified by macros, be that in the compiler or in pure hy macros. .sp \fBHyObject\fP is not intended to be used directly to instantiate Hy models, but only as a mixin for other classes. .SS Compound Models .sp Parenthesized and bracketed lists are parsed as compound models by the Hy parser. .SS HyList .sp \fBhy.models.list.HyList\fP is the base class of "iterable" Hy models. Its basic use is to represent bracketed \fB[]\fP lists, which, when used as a top\-level expression, translate to Python list literals in the compilation phase. .sp Adding a HyList to another iterable object reuses the class of the left\-hand\-side object, a useful behavior when you want to concatenate Hy objects in a macro, for instance. .SS HyExpression .sp \fBhy.models.expression.HyExpression\fP inherits \fI\%HyList\fP for parenthesized \fB()\fP expressions. The compilation result of those expressions depends on the first element of the list: the compiler dispatches expressions between compiler special\-forms, user\-defined macros, and regular Python function calls. .SS HyDict .sp \fBhy.models.dict.HyDict\fP inherits \fI\%HyList\fP for curly\-bracketed \fB{}\fP expressions, which compile down to a Python dictionary literal. .sp The decision of using a list instead of a dict as the base class for \fBHyDict\fP allows easier manipulation of dicts in macros, with the added benefit of allowing compound expressions as dict keys (as, for instance, the \fI\%HyExpression\fP Python class isn\(aqt hashable). .SS Atomic Models .sp In the input stream, double\-quoted strings, respecting the Python notation for strings, are parsed as a single token, which is directly parsed as a \fI\%HyString\fP\&. .sp An uninterrupted string of characters, excluding spaces, brackets, quotes, double\-quotes and comments, is parsed as an identifier. .sp Identifiers are resolved to atomic models during the parsing phase in the following order: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fI\%HyInteger\fP .IP \(bu 2 \fI\%HyFloat\fP .IP \(bu 2 \fI\%HyComplex\fP (if the atom isn\(aqt a bare \fBj\fP) .IP \(bu 2 \fI\%HyKeyword\fP (if the atom starts with \fB:\fP) .IP \(bu 2 \fI\%HySymbol\fP .UNINDENT .UNINDENT .UNINDENT .SS HyString .sp \fBhy.models.string.HyString\fP is the base class of string\-equivalent Hy models. It also represents double\-quoted string literals, \fB""\fP, which compile down to unicode string literals in Python. \fBHyStrings\fP inherit unicode objects in Python 2, and string objects in Python 3 (and are therefore not encoding\-dependent). .sp \fBHyString\fP based models are immutable. .sp Hy literal strings can span multiple lines, and are considered by the parser as a single unit, respecting the Python escapes for unicode strings. .SS Numeric Models .sp \fBhy.models.integer.HyInteger\fP represents integer literals (using the \fBlong\fP type on Python 2, and \fBint\fP on Python 3). .sp \fBhy.models.float.HyFloat\fP represents floating\-point literals. .sp \fBhy.models.complex.HyComplex\fP represents complex literals. .sp Numeric models are parsed using the corresponding Python routine, and valid numeric python literals will be turned into their Hy counterpart. .SS HySymbol .sp \fBhy.models.symbol.HySymbol\fP is the model used to represent symbols in the Hy language. It inherits \fI\%HyString\fP\&. .sp \fBHySymbol\fP objects are mangled in the parsing phase, to help Python interoperability: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Symbols surrounded by asterisks (\fB*\fP) are turned into uppercase; .IP \(bu 2 Dashes (\fB\-\fP) are turned into underscores (\fB_\fP); .IP \(bu 2 One trailing question mark (\fB?\fP) is turned into a leading \fBis_\fP\&. .UNINDENT .UNINDENT .UNINDENT .sp Caveat: as the mangling is done during the parsing phase, it is possible to programmatically generate HySymbols that can\(aqt be generated with Hy source code. Such a mechanism is used by gensym to generate "uninterned" symbols. .SS HyKeyword .sp \fBhy.models.keyword.HyKeyword\fP represents keywords in Hy. Keywords are symbols starting with a \fB:\fP\&. The class inherits \fI\%HyString\fP\&. .sp To distinguish \fI\%HyKeywords\fP from \fI\%HySymbols\fP, without the possibility of (involuntary) clashes, the private\-use unicode character \fB"\euFDD0"\fP is prepended to the keyword literal before storage. .SS Cons Cells .sp \fBhy.models.cons.HyCons\fP is a representation of Python\-friendly \fI\%cons cells\fP\&. Cons cells are especially useful to mimic features of "usual" LISP variants such as Scheme or Common Lisp. .sp A cons cell is a 2\-item object, containing a \fBcar\fP (head) and a \fBcdr\fP (tail). In some Lisp variants, the cons cell is the fundamental building block, and S\-expressions are actually represented as linked lists of cons cells. This is not the case in Hy, as the usual expressions are made of Python lists wrapped in a \fBHyExpression\fP\&. However, the \fBHyCons\fP mimicks the behavior of "usual" Lisp variants thusly: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fB(cons something nil)\fP is \fB(HyExpression [something])\fP .IP \(bu 2 \fB(cons something some\-list)\fP is \fB((type some\-list) (+ [something] some\-list))\fP (if \fBsome\-list\fP inherits from \fBlist\fP). .IP \(bu 2 \fB(get (cons a b) 0)\fP is \fBa\fP .IP \(bu 2 \fB(slice (cons a b) 1)\fP is \fBb\fP .UNINDENT .UNINDENT .UNINDENT .sp Hy supports a dotted\-list syntax, where \fB\(aq(a . b)\fP means \fB(cons \(aqa \(aqb)\fP and \fB\(aq(a b . c)\fP means \fB(cons \(aqa (cons \(aqb \(aqc))\fP\&. If the compiler encounters a cons cell at the top level, it raises a compilation error. .sp \fBHyCons\fP wraps the passed arguments (car and cdr) in Hy types, to ease the manipulation of cons cells in a macro context. .SS Hy Internal Theory .SS Overview .sp The Hy internals work by acting as a front\-end to Python bytecode, so that Hy itself compiles down to Python Bytecode, allowing an unmodified Python runtime to run Hy code, without even noticing it. .sp The way we do this is by translating Hy into an internal Python AST datastructure, and building that AST down into Python bytecode using modules from the Python standard library, so that we don\(aqt have to duplicate all the work of the Python internals for every single Python release. .sp Hy works in four stages. The following sections will cover each step of Hy from source to runtime. .SS Steps 1 and 2: Tokenizing and Parsing .sp The first stage of compiling Hy is to lex the source into tokens that we can deal with. We use a project called rply, which is a really nice (and fast) parser, written in a subset of Python called rpython. .sp The lexing code is all defined in \fBhy.lex.lexer\fP\&. This code is mostly just defining the Hy grammar, and all the actual hard parts are taken care of by rply \-\- we just define "callbacks" for rply in \fBhy.lex.parser\fP, which takes the tokens generated, and returns the Hy models. .sp You can think of the Hy models as the "AST" for Hy, it\(aqs what Macros operate on (directly), and it\(aqs what the compiler uses when it compiles Hy down. .sp \fBSEE ALSO:\fP .INDENT 0.0 .INDENT 3.5 Section \fI\%Hy Models\fP for more information on Hy models and what they mean. .UNINDENT .UNINDENT .SS Step 3: Hy Compilation to Python AST .sp This is where most of the magic in Hy happens. This is where we take Hy AST (the models), and compile them into Python AST. A couple of funky things happen here to work past a few problems in AST, and working in the compiler is some of the most important work we do have. .sp The compiler is a bit complex, so don\(aqt feel bad if you don\(aqt grok it on the first shot, it may take a bit of time to get right. .sp The main entry\-point to the Compiler is \fBHyASTCompiler.compile\fP\&. This method is invoked, and the only real "public" method on the class (that is to say, we don\(aqt really promise the API beyond that method). .sp In fact, even internally, we don\(aqt recurse directly hardly ever, we almost always force the Hy tree through \fBcompile\fP, and will often do this with sub\-elements of an expression that we have. It\(aqs up to the Type\-based dispatcher to properly dispatch sub\-elements. .sp All methods that preform a compilation are marked with the \fB@builds()\fP decorator. You can either pass the class of the Hy model that it compiles, or you can use a string for expressions. I\(aqll clear this up in a second. .SS First Stage Type\-Dispatch .sp Let\(aqs start in the \fBcompile\fP method. The first thing we do is check the Type of the thing we\(aqre building. We look up to see if we have a method that can build the \fBtype()\fP that we have, and dispatch to the method that can handle it. If we don\(aqt have any methods that can build that type, we raise an internal \fBException\fP\&. .sp For instance, if we have a \fBHyString\fP, we have an almost 1\-to\-1 mapping of Hy AST to Python AST. The \fBcompile_string\fP method takes the \fBHyString\fP, and returns an \fBast.Str()\fP that\(aqs populated with the correct line\-numbers and content. .SS Macro\-Expand .sp If we get a \fBHyExpression\fP, we\(aqll attempt to see if this is a known Macro, and push to have it expanded by invoking \fBhy.macros.macroexpand\fP, then push the result back into \fBHyASTCompiler.compile\fP\&. .SS Second Stage Expression\-Dispatch .sp The only special case is the \fBHyExpression\fP, since we need to create different AST depending on the special form in question. For instance, when we hit an \fB(if true true false)\fP, we need to generate a \fBast.If\fP, and properly compile the sub\-nodes. This is where the \fB@builds()\fP with a String as an argument comes in. .sp For the \fBcompile_expression\fP (which is defined with an \fB@builds(HyExpression)\fP) will dispatch based on the string of the first argument. If, for some reason, the first argument is not a string, it will properly handle that case as well (most likely by raising an \fBException\fP). .sp If the String isn\(aqt known to Hy, it will default to create an \fBast.Call\fP, which will try to do a runtime call (in Python, something like \fBfoo()\fP). .SS Issues Hit with Python AST .sp Python AST is great; it\(aqs what\(aqs enabled us to write such a powerful project on top of Python without having to fight Python too hard. Like anything, we\(aqve had our fair share of issues, and here\(aqs a short list of the common ones you might run into. .sp \fIPython differentiates between Statements and Expressions\fP\&. .sp This might not sound like a big deal \-\- in fact, to most Python programmers, this will shortly become a "Well, yeah" moment. .sp In Python, doing something like: .sp \fBprint for x in range(10): pass\fP, because \fBprint\fP prints expressions, and \fBfor\fP isn\(aqt an expression, it\(aqs a control flow statement. Things like \fB1 + 1\fP are Expressions, as is \fBlambda x: 1 + x\fP, but other language features, such as \fBif\fP, \fBfor\fP, or \fBwhile\fP are statements. .sp Since they have no "value" to Python, this makes working in Hy hard, since doing something like \fB(print (if true true false))\fP is not just common, it\(aqs expected. .sp As a result, we auto\-mangle things using a \fBResult\fP object, where we offer up any \fBast.stmt\fP that need to get run, and a single \fBast.expr\fP that can be used to get the value of whatever was just run. Hy does this by forcing assignment to things while running. .sp As example, the Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (if true true false)) .ft P .fi .UNINDENT .UNINDENT .sp Will turn into: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C if True: _mangled_name_here = True else: _mangled_name_here = False print _mangled_name_here .ft P .fi .UNINDENT .UNINDENT .sp OK, that was a bit of a lie, since we actually turn that statement into: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C print True if True else False .ft P .fi .UNINDENT .UNINDENT .sp By forcing things into an \fBast.expr\fP if we can, but the general idea holds. .SS Step 4: Python Bytecode Output and Runtime .sp After we have a Python AST tree that\(aqs complete, we can try and compile it to Python bytecode by pushing it through \fBeval\fP\&. From here on out, we\(aqre no longer in control, and Python is taking care of everything. This is why things like Python tracebacks, pdb and django apps work. .SS Hy Macros .SS Using gensym for Safer Macros .sp When writing macros, one must be careful to avoid capturing external variables or using variable names that might conflict with user code. .sp We will use an example macro \fBnif\fP (see \fI\%http://letoverlambda.com/index.cl/guest/chap3.html#sec_5\fP for a more complete description.) \fBnif\fP is an example, something like a numeric \fBif\fP, where based on the expression, one of the 3 forms is called depending on if the expression is positive, zero or negative. .sp A first pass might be something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro nif [expr pos\-form zero\-form neg\-form] \(ga(let [[obscure\-name ~expr]] (cond [(pos? obscure\-name) ~pos\-form] [(zero? obscure\-name) ~zero\-form] [(neg? obscure\-name) ~neg\-form]))) .ft P .fi .UNINDENT .UNINDENT .sp where \fBobsure\-name\fP is an attempt to pick some variable name as not to conflict with other code. But of course, while well\-intentioned, this is no guarantee. .sp The method gensym is designed to generate a new, unique symbol for just such an occasion. A much better version of \fBnif\fP would be: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro nif [expr pos\-form zero\-form neg\-form] (let [[g (gensym)]] \(ga(let [[~g ~expr]] (cond [(pos? ~g) ~pos\-form] [(zero? ~g) ~zero\-form] [(neg? ~g) ~neg\-form])))) .ft P .fi .UNINDENT .UNINDENT .sp This is an easy case, since there is only one symbol. But if there is a need for several gensym\(aqs there is a second macro with\-gensyms that basically expands to a series of \fBlet\fP statements: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with\-gensyms [a b c] ...) .ft P .fi .UNINDENT .UNINDENT .sp expands to: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (let [[a (gensym) [b (gensym) [c (gensym)]] ...) .ft P .fi .UNINDENT .UNINDENT .sp so our re\-written \fBnif\fP would look like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro nif [expr pos\-form zero\-form neg\-form] (with\-gensyms [g] \(ga(let [[~g ~expr]] (cond [(pos? ~g) ~pos\-form] [(zero? ~g) ~zero\-form] [(neg? ~g) ~neg\-form])))) .ft P .fi .UNINDENT .UNINDENT .sp Finally, though we can make a new macro that does all this for us. defmacro/g! will take all symbols that begin with \fBg!\fP and automatically call \fBgensym\fP with the remainder of the symbol. So \fBg!a\fP would become \fB(gensym "a")\fP\&. .sp Our final version of \fBnif\fP, built with \fBdefmacro/g!\fP becomes: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro/g! nif [expr pos\-form zero\-form neg\-form] \(ga(let [[~g!res ~expr]] (cond [(pos? ~g!res) ~pos\-form] [(zero? ~g!res) ~zero\-form] [(neg? ~g!res) ~neg\-form])))) .ft P .fi .UNINDENT .UNINDENT .SS Checking Macro Arguments and Raising Exceptions .SS Hy Compiler Built\-Ins .SH CONTRIBUTOR MODULES INDEX .sp Contents: .SS Anaphoric Macros .sp New in version 0.9.12. .sp The anaphoric macros module makes functional programming in Hy very concise and easy to read. .INDENT 0.0 .INDENT 3.5 An anaphoric macro is a type of programming macro that deliberately captures some form supplied to the macro which may be referred to by an anaphor (an expression referring to another). \(em Wikipedia (\fI\%http://en.wikipedia.org/wiki/Anaphoric_macro\fP) .UNINDENT .UNINDENT .SS Macros .SS ap\-if .sp Usage: \fB(ap\-if (foo) (print it))\fP .sp Evaluates the first form for truthiness, and bind it to \fBit\fP in both the true and false branches. .SS ap\-each .sp Usage: \fB(ap\-each [1 2 3 4 5] (print it))\fP .sp Evaluate the form for each element in the list for side\-effects. .SS ap\-each\-while .sp Usage: \fB(ap\-each\-while list pred body)\fP .sp Evaluate the form for each element where the predicate form returns \fBTrue\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (ap\-each\-while [1 2 3 4 5 6] (< it 4) (print it)) 1 2 3 .ft P .fi .UNINDENT .UNINDENT .SS ap\-map .sp Usage: \fB(ap\-map form list)\fP .sp The anaphoric form of map works just like regular map except that instead of a function object it takes a Hy form. The special name \fBit\fP is bound to the current object from the list in the iteration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (ap\-map (* it 2) [1 2 3])) [2, 4, 6] .ft P .fi .UNINDENT .UNINDENT .SS ap\-map\-when .sp Usage: \fB(ap\-map\-when predfn rep list)\fP .sp Evaluate a mapping over the list using a predicate function to determin when to apply the form. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (ap\-map\-when odd? (* it 2) [1 2 3 4])) [2, 2, 6, 4] => (list (ap\-map\-when even? (* it 2) [1 2 3 4])) [1, 4, 3, 8] .ft P .fi .UNINDENT .UNINDENT .SS ap\-filter .sp Usage: \fB(ap\-filter form list)\fP .sp As with \fBap\-map\fP we take a special form instead of a function to filter the elements of the list. The special name \fBit\fP is bound to the current element in the iteration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (ap\-filter (> (* it 2) 6) [1 2 3 4 5])) [4, 5] .ft P .fi .UNINDENT .UNINDENT .SS ap\-reject .sp Usage: \fB(ap\-reject form list)\fP .sp This function does the opposite of \fBap\-filter\fP, it rejects the elements passing the predicate . The special name \fBit\fP is bound to the current element in the iteration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (ap\-reject (> (* it 2) 6) [1 2 3 4 5])) [1, 2, 3] .ft P .fi .UNINDENT .UNINDENT .SS ap\-dotimes .sp Usage \fB(ap\-dotimes n body)\fP .sp This function evaluates the body \fIn\fP times, with the special variable \fBit\fP bound from \fI0\fP to \fI1\-n\fP\&. It is useful for side\-effects. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv n []) => (ap\-dotimes 3 (.append n it)) => n [0, 1, 2] .ft P .fi .UNINDENT .UNINDENT .SS ap\-first .sp Usage \fB(ap\-first predfn list)\fP .sp This function returns the first element that passes the predicate or \fBNone\fP, with the special variable \fBit\fP bound to the current element in iteration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C =>(ap\-first (> it 5) (range 10)) 6 .ft P .fi .UNINDENT .UNINDENT .SS ap\-last .sp Usage \fB(ap\-last predfn list)\fP .sp This function returns the last element that passes the predicate or \fBNone\fP, with the special variable \fBit\fP bound to the current element in iteration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C =>(ap\-last (> it 5) (range 10)) 9 .ft P .fi .UNINDENT .UNINDENT .SS ap\-reduce .sp Usage \fB(ap\-reduce form list &optional initial\-value)\fP .sp This function returns the result of applying form to the first 2 elements in the body and applying the result and the 3rd element etc. until the list is exhausted. Optionally an initial value can be supplied so the function will be applied to initial value and the first element instead. This exposes the element being iterated as \fBit\fP and the current accumulated value as \fBacc\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C =>(ap\-reduce (+ it acc) (range 10)) 45 .ft P .fi .UNINDENT .UNINDENT .SS loop/recur .sp New in version 0.10.0. .sp The \fBloop\fP / \fBrecur\fP macro gives programmers a simple way to use tail\-call optimization (TCO) in their Hy code. .INDENT 0.0 .INDENT 3.5 A tail call is a subroutine call that happens inside another procedure as its final action; it may produce a return value which is then immediately returned by the calling procedure. If any call that a subroutine performs, such that it might eventually lead to this same subroutine being called again down the call chain, is in tail position, such a subroutine is said to be tail\-recursive, which is a special case of recursion. Tail calls are significant because they can be implemented without adding a new stack frame to the call stack. Most of the frame of the current procedure is not needed any more, and it can be replaced by the frame of the tail call. The program can then jump to the called subroutine. Producing such code instead of a standard call sequence is called tail call elimination, or tail call optimization. Tail call elimination allows procedure calls in tail position to be implemented as efficiently as goto statements, thus allowing efficient structured programming. \(em Wikipedia (\fI\%http://en.wikipedia.org/wiki/Tail_call\fP) .UNINDENT .UNINDENT .SS Macros .SS loop .sp \fBloop\fP establishes a recursion point. With \fBloop\fP, \fBrecur\fP rebinds the variables set in the recursion point and sends code execution back to that recursion point. If \fBrecur\fP is used in a non\-tail position, an exception is thrown. .sp Usage: \fI(loop bindings &rest body)\fP .sp Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require hy.contrib.loop) (defn factorial [n] (loop [[i n] [acc 1]] (if (zero? i) acc (recur (dec i) (* acc i))))) (factorial 1000) .ft P .fi .UNINDENT .UNINDENT .SS defmulti .sp New in version 0.10.0. .sp \fBdefmulti\fP lets you arity\-overload a function by the given number of args and/or kwargs. Inspired by Clojure\(aqs take on \fBdefn\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (require hy.contrib.multi) => (defmulti fun \&... ([a] "a") \&... ([a b] "a b") \&... ([a b c] "a b c")) => (fun 1) "a" => (fun 1 2) "a b" => (fun 1 2 3) "a b c" .ft P .fi .UNINDENT .UNINDENT .SH HACKING ON HY .SS Join our Hyve! .sp Please come hack on Hy! .sp Please come hang out with us on \fB#hy\fP on \fBirc.freenode.net\fP! .sp Please talk about it on Twitter with the \fB#hy\fP hashtag! .sp Please blog about it! .sp Please don\(aqt spraypaint it on your neighbor\(aqs fence (without asking nicely)! .SS Hack! .sp Do this: .INDENT 0.0 .IP 1. 3 Create a \fI\%virtual environment\fP: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ virtualenv venv .ft P .fi .UNINDENT .UNINDENT .sp and activate it: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ . venv/bin/activate .ft P .fi .UNINDENT .UNINDENT .sp or use \fI\%virtualenvwrapper\fP to create and manage your virtual environment: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ mkvirtualenv hy $ workon hy .ft P .fi .UNINDENT .UNINDENT .IP 2. 3 Get the source code: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ git clone https://github.com/hylang/hy.git .ft P .fi .UNINDENT .UNINDENT .sp or use your fork: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ git clone git@github.com:/hy.git .ft P .fi .UNINDENT .UNINDENT .IP 3. 3 Install for hacking: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ cd hy/ $ pip install \-e . .ft P .fi .UNINDENT .UNINDENT .IP 4. 3 Install other develop\-y requirements: .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ pip install \-r requirements\-dev.txt .ft P .fi .UNINDENT .UNINDENT .IP 5. 3 Do awesome things; make someone shriek in delight/disgust at what you have wrought. .UNINDENT .SS Test! .sp Tests are located in \fBtests/\fP\&. We use \fI\%nose\fP\&. .sp To run the tests: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ nosetests .ft P .fi .UNINDENT .UNINDENT .sp Write tests\-\-\-tests are good! .sp Also, it is good to run the tests for all the platforms supported and for PEP 8 compliant code. You can do so by running tox: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tox .ft P .fi .UNINDENT .UNINDENT .SS Document! .sp Documentation is located in \fBdocs/\fP\&. We use \fI\%Sphinx\fP\&. .sp To build the docs in HTML: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd docs $ make html .ft P .fi .UNINDENT .UNINDENT .sp Write docs\-\-\-docs are good! Even this doc! .SS Contributing .sp Contributions are welcome & greatly appreciated, every little bit helps in making Hy more awesome. .sp Pull requests are great! We love them; here is a quick guide: .INDENT 0.0 .IP \(bu 2 Fork the repo and create a topic branch for a feature/fix. Avoid making changes directly on the master branch. .IP \(bu 2 All incoming features should be accompanied with tests. .IP \(bu 2 Before you submit a PR, please run the tests and check your code against the style guide. You can do both of these things at once: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C $ make d .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Make commits into logical units, so that it is easier to track & navigate later. Before submitting a PR, try squashing the commits into changesets that are easy to come back to later. Also, make sure you don\(aqt leave spurious whitespace in the changesets; this avoids creation of whitespace fix commits later. .IP \(bu 2 As far as commit messages go, try to adhere to the following: .INDENT 2.0 .IP \(bu 2 Try sticking to the 50 character limit for the first line of Git commit messages. .IP \(bu 2 For more detail/explainations, follow this up with a blank line and continue describing the commit in detail. .UNINDENT .IP \(bu 2 Finally, add yourself to the AUTHORS file (as a separate commit): you deserve it :) .IP \(bu 2 All incoming changes need to be acked by 2 different members of Hylang\(aqs core team. Additional review is clearly welcome, but we need a minimum of 2 signoffs for any change. .IP \(bu 2 If a core member is sending in a PR, please find 2 core members that doesn\(aqt include the PR submitter. The idea here is that one can work with the PR author, and a second acks the entire change set. .IP \(bu 2 For documentation & other trivial changes, we\(aqre good to merge after one ACK. We\(aqve got low coverage, so it\(aqd be great to keep that barrier low. .UNINDENT .SS Core Team .sp The core development team of Hy consists of following developers: .INDENT 0.0 .IP \(bu 2 \fI\%Julien Danjou\fP .IP \(bu 2 \fI\%Morten Linderud\fP .IP \(bu 2 \fI\%J Kenneth King\fP .IP \(bu 2 \fI\%Gergely Nagy\fP .IP \(bu 2 \fI\%Tuukka Turto\fP .IP \(bu 2 \fI\%Karen Rustad\fP .IP \(bu 2 \fI\%Abhishek L\fP .IP \(bu 2 \fI\%Christopher Allan Webber\fP .IP \(bu 2 \fI\%Konrad Hinsen\fP .IP \(bu 2 \fI\%Will Kahn\-Greene\fP .IP \(bu 2 \fI\%Paul Tagliamonte\fP .IP \(bu 2 \fI\%Nicolas Dandrimont\fP .IP \(bu 2 \fI\%Bob Tolbert\fP .IP \(bu 2 \fI\%Berker Peksag\fP .IP \(bu 2 \fI\%Clinton N. Dreisbach\fP .IP \(bu 2 \fI\%han semaj\fP .UNINDENT .SH AUTHOR Paul Tagliamonte .SH COPYRIGHT 2013-2016, Paul Tagliamonte .\" Generated by docutils manpage writer. .