.\" Man page generated from reStructuredText. . .TH "HY" "1" "December 10, 2020" "0.19" "hy" .SH NAME hy \- hy 0.19.0 . .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 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 \fI\%irc://chat.freenode.net/hy\fP .TP .B Stack Overflow \fI\%The [hy] tag\fP .UNINDENT .sp Hy is a Lisp dialect that\(aqs embedded in Python. Since Hy transforms its Lisp code into Python abstract syntax tree (AST) objects, you have the whole beautiful world of Python at your fingertips, in Lisp form. .sp To install the latest stable release of Hy, just use the command \fBpip3 install \-\-user hy\fP\&. Then you can start an interactive read\-eval\-print loop (REPL) with the command \fBhy\fP, or run a Hy program with \fBhy myprogram.hy\fP\&. .SH WHY HY? .sp Hy is a multi\-paradigm general\-purpose programming language in the \fI\%Lisp family\fP\&. It\(aqs implemented as a kind of alternative syntax for Python. Compared to Python, Hy offers a variety of extra features, generalizations, and syntactic simplifications, as would be expected of a Lisp. Compared to other Lisps, Hy provides direct access to Python\(aqs built\-ins and third\-party Python libraries, while allowing you to freely mix imperative, functional, and object\-oriented styles of programming. .SS Hy versus Python .sp The first thing a Python programmer will notice about Hy is that it has Lisp\(aqs traditional parenthesis\-heavy prefix syntax in place of Python\(aqs C\-like infix syntax. For example, \fBprint("The answer is", 2 + object.method(arg))\fP could be written \fB(print "The answer is" (+ 2 (.method object arg)))\fP in Hy. Consequently, Hy is free\-form: structure is indicated by parentheses rather than whitespace, making it convenient for command\-line use. .sp As in other Lisps, the value of a simplistic syntax is that it facilitates Lisp\(aqs signature feature: \fI\%metaprogramming\fP through macros, which are functions that manipulate code objects at compile time to produce new code objects, which are then executed as if they had been part of the original code. In fact, Hy allows arbitrary computation at compile\-time. For example, here\(aqs a simple macro that implements a C\-style do\-while loop, which executes its body for as long as the condition is true, but at least once. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro do\-while [condition &rest body] \(ga(do ~body (while ~condition ~body))) (setv x 0) (do\-while x (print "This line is executed once.")) .ft P .fi .UNINDENT .UNINDENT .sp Hy also removes Python\(aqs restrictions on mixing expressions and statements, allowing for more direct and functional code. For example, Python doesn\(aqt allow \fI\%with\fP blocks, which close a resource once you\(aqre done using it, to return values. They can only execute a set of statements: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C with open("foo") as o: f1 = o.read() with open("bar") as o: f2 = o.read() print(len(f1) + len(f2)) .ft P .fi .UNINDENT .UNINDENT .sp In Hy, with returns the value of its last body form, so you can use it like an ordinary function call: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (+ (len (with [o (open "foo")] (.read o)) (len (with [o (open "bar")] (.read o)))))) .ft P .fi .UNINDENT .UNINDENT .sp To be even more concise, you can put a \fBwith\fP form in a generator expression: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (sum (gfor filename ["foo" "bar"] (len (with [o (open filename)] (.read o)))))) .ft P .fi .UNINDENT .UNINDENT .sp Finally, Hy offers several generalizations to Python\(aqs binary operators. Operators can be given more than two arguments (e.g., \fB(+ 1 2 3)\fP), including augmented assignment operators (e.g., \fB(+= x 1 2 3)\fP). They are also provided as ordinary first\-class functions of the same name, allowing them to be passed to higher\-order functions: \fB(sum xs)\fP could be written \fB(reduce + xs)\fP\&. .sp The Hy compiler works by reading Hy source code into Hy model objects and compiling the Hy model objects into Python abstract syntax tree (\fI\%ast\fP) objects. Python AST objects can then be compiled and run by Python itself, byte\-compiled for faster execution later, or rendered into Python source code. You can even mix Python and Hy code in the same project, or even the same file, which can be a good way to get your feet wet in Hy. .SS Hy versus other Lisps .sp At run\-time, Hy is essentially Python code. Thus, while Hy\(aqs design owes a lot to \fI\%Clojure\fP, it is more tightly coupled to Python than Clojure is to Java; a better analogy is \fI\%CoffeeScript\(aqs\fP relationship to JavaScript. Python\(aqs built\-in \fI\%functions\fP and \fI\%data structures\fP are directly available: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (int "deadbeef" :base 16)) ; 3735928559 (print (len [1 10 100])) ; 3 .ft P .fi .UNINDENT .UNINDENT .sp The same goes for third\-party Python libraries from \fI\%PyPI\fP and elsewhere. Here\(aqs a tiny \fI\%CherryPy\fP web application in Hy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import cherrypy) (defclass HelloWorld [] #@(cherrypy.expose (defn index [self] "Hello World!"))) (cherrypy.quickstart (HelloWorld)) .ft P .fi .UNINDENT .UNINDENT .sp You can even run Hy on \fI\%PyPy\fP for a particularly speedy Lisp. .sp Like all Lisps, Hy is \fI\%homoiconic\fP\&. Its syntax is represented not with cons cells or with Python\(aqs basic data structures, but with simple subclasses of Python\(aqs basic data structures called models\&. Using models in place of plain \fBlist\fPs, \fBset\fPs, and so on has two purposes: models can keep track of their line and column numbers for the benefit of error messages, and models can represent syntactic features that the corresponding primitive type can\(aqt, such as the order in which elements appear in a set literal. However, models can be concatenated and indexed just like plain lists, and you can return ordinary Python types from a macro or give them to \fBeval\fP and Hy will automatically promote them to models. .sp Hy takes much of its semantics from Python. For example, Hy is a Lisp\-1 because Python functions use the same namespace as objects that aren\(aqt functions. In general, any Python code should be possible to literally translate to Hy. At the same time, Hy goes to some lengths to allow you to do typical Lisp things that aren\(aqt straightforward in Python. For example, Hy provides the aforementioned mixing of statements and expressions, name mangling that transparently converts symbols with names like \fBvalid?\fP to Python\-legal identifiers, and a let macro to provide block\-level scoping in place of Python\(aqs usual function\-level scoping. .sp Overall, Hy, like Common Lisp, is intended to be an unopinionated big\-tent language that lets you do what you want. If you\(aqre interested in a more small\-and\-beautiful approach to Lisp, in the style of Scheme, check out \fI\%Hissp\fP, another Lisp embedded in Python that was created by a Hy developer. .SH TUTORIAL [image: Karen Rustard's Cuddles] [image] .sp This chapter provides a quick introduction to Hy. It assumes a basic background in programming, but no specific prior knowledge of Python or Lisp. .SS Lisp\-stick on a Python .sp Let\(aqs start with the classic: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "Hy, world!") .ft P .fi .UNINDENT .UNINDENT .sp This program calls the \fI\%print()\fP function, which, like all of Python\(aqs \fI\%built\-in functions\fP, is available in Hy. .sp All of Python\(aqs \fI\%binary and unary operators\fP are available, too, although \fB==\fP is spelled \fB=\fP in deference to Lisp tradition. Here\(aqs how we\(aqd use the addition operator \fB+\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (+ 1 3) .ft P .fi .UNINDENT .UNINDENT .sp This code returns \fB4\fP\&. It\(aqs equivalent to \fB1 + 3\fP in Python and many other languages. Languages in the \fI\%Lisp\fP family, including Hy, use a prefix syntax: \fB+\fP, just like \fBprint\fP or \fBsqrt\fP, appears before all of its arguments. The call is delimited by parentheses, but the opening parenthesis appears before the operator being called instead of after it, so instead of \fBsqrt(2)\fP, we write \fB(sqrt 2)\fP\&. Multiple arguments, such as the two integers in \fB(+ 1 3)\fP, are separated by whitespace. Many operators, including \fB+\fP, allow more than two arguments: \fB(+ 1 2 3)\fP is equivalent to \fB1 + 2 + 3\fP\&. .sp Here\(aqs a more complex example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (\- (* (+ 1 3 88) 2) 8) .ft P .fi .UNINDENT .UNINDENT .sp This code returns \fB176\fP\&. Why? We can see the infix equivalent with the command \fBecho "(\- (* (+ 1 3 88) 2) 8)" | hy2py\fP, which returns the Python code corresponding to the given Hy code, or by passing the \fB\-\-spy\fP option to Hy when starting the REPL, which shows the Python equivalent of each input line before the result. The infix equivalent in this case is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ((1 + 3 + 88) * 2) \- 8 .ft P .fi .UNINDENT .UNINDENT .sp To evaluate this infix expression, you\(aqd of course evaluate the innermost parenthesized expression first and work your way outwards. The same goes for Lisp. Here\(aqs what we\(aqd get by evaluating the above Hy code one step at a time: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (\- (* (+ 1 3 88) 2) 8) (\- (* 92 2) 8) (\- 184 8) 176 .ft P .fi .UNINDENT .UNINDENT .sp The basic unit of Lisp syntax, which is similar to a C or Python expression, is the \fBform\fP\&. \fB92\fP, \fB*\fP, and \fB(* 92 2)\fP are all forms. A Lisp program consists of a sequence of forms nested within forms. Forms are typically separated from each other by whitespace, but some forms, such as string literals (\fB"Hy, world!"\fP), can contain whitespace themselves. An \fBexpression\fP is a form enclosed in parentheses; its first child form, called the \fBhead\fP, determines what the expression does, and should generally be a function, macro, or special operator. Functions are the most ordinary sort of head, whereas macros (described in more detail below) are functions executed at compile\-time instead and return code to be executed at run\-time. Special operators are one of a fixed set of names that are hard\-coded into the compiler, and used to implement everything else. .sp Comments start with a \fB;\fP character and continue till the end of the line. A comment is functionally equivalent to whitespace. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (** 2 64)) ; Max 64\-bit unsigned integer value .ft P .fi .UNINDENT .UNINDENT .sp Although \fB#\fP isn\(aqt a comment character in Hy, a Hy program can begin with a \fI\%shebang line\fP, which Hy itself will ignore: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #!/usr/bin/env hy (print "Make me executable, and run me!") .ft P .fi .UNINDENT .UNINDENT .SS Literals .sp Hy has literal syntax for all of the same data types that Python does. Here\(aqs an example of Hy code for each type and the Python equivalent. .TS center; |l|l|l|. _ T{ Hy T} T{ Python T} T{ Type T} _ T{ \fB1\fP T} T{ \fB1\fP T} T{ \fI\%int\fP T} _ T{ \fB1.2\fP T} T{ \fB1.2\fP T} T{ \fI\%float\fP T} _ T{ \fB4j\fP T} T{ \fB4j\fP T} T{ \fI\%complex\fP T} _ T{ \fBTrue\fP T} T{ \fBTrue\fP T} T{ \fI\%bool\fP T} _ T{ \fBNone\fP T} T{ \fBNone\fP T} T{ \fBNoneType\fP T} _ T{ \fB"hy"\fP T} T{ \fB\(aqhy\(aq\fP T} T{ \fI\%str\fP T} _ T{ \fBb"hy"\fP T} T{ \fBb\(aqhy\(aq\fP T} T{ \fI\%bytes\fP T} _ T{ \fB(, 1 2 3)\fP T} T{ \fB(1, 2, 3)\fP T} T{ \fI\%tuple\fP T} _ T{ \fB[1 2 3]\fP T} T{ \fB[1, 2, 3]\fP T} T{ \fI\%list\fP T} _ T{ \fB#{1 2 3}\fP T} T{ \fB{1, 2, 3}\fP T} T{ \fI\%set\fP T} _ T{ \fB{1 2 3 4}\fP T} T{ \fB{1: 2, 3: 4}\fP T} T{ \fI\%dict\fP T} _ .TE .sp In addition, Hy has a Clojure\-style literal syntax for \fI\%fractions.Fraction\fP: \fB1/3\fP is equivalent to \fBfractions.Fraction(1, 3)\fP\&. .sp The Hy REPL prints output in Python syntax by default: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => [1 2 3] [1, 2, 3] .ft P .fi .UNINDENT .UNINDENT .sp But if you start Hy like this (a shell alias might be helpful): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ hy \-\-repl\-output\-fn=hy.contrib.hy\-repr.hy\-repr .ft P .fi .UNINDENT .UNINDENT .sp the interactive mode will use hy\-repr\-fn instead of Python\(aqs native \fBrepr\fP function to print out values, so you\(aqll see values in Hy syntax: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => [1 2 3] [1 2 3] .ft P .fi .UNINDENT .UNINDENT .SS Basic operations .sp Set variables with setv: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv zone\-plane 8) .ft P .fi .UNINDENT .UNINDENT .sp Access the elements of a list, dictionary, or other data structure with get: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv fruit ["apple" "banana" "cantaloupe"]) (print (get fruit 0)) ; => apple (setv (get fruit 1) "durian") (print (get fruit 1)) ; => durian .ft P .fi .UNINDENT .UNINDENT .sp Access a range of elements in an ordered structure with cut: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (cut "abcdef" 1 4)) ; => bcd .ft P .fi .UNINDENT .UNINDENT .sp Conditional logic can be built with if: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (if (= 1 1) (print "Math works. The universe is safe.") (print "Math has failed. The universe is doomed.")) .ft P .fi .UNINDENT .UNINDENT .sp As in this example, \fBif\fP is called like \fB(if CONDITION THEN ELSE)\fP\&. It executes and returns the form \fBTHEN\fP if \fBCONDITION\fP is true (according to \fI\%bool\fP) and \fBELSE\fP otherwise. If \fBELSE\fP is omitted, \fBNone\fP is used in its place. .sp What if you want to use more than form in place of the \fBTHEN\fP or \fBELSE\fP clauses, or in place of \fBCONDITION\fP, for that matter? Use the special operator do (known more traditionally in Lisp as \fBprogn\fP), which combines several forms into one, returning the last: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (if (do (print "Let\(aqs check.") (= 1 1)) (do (print "Math works.") (print "The universe is safe.")) (do (print "Math has failed.") (print "The universe is doomed."))) .ft P .fi .UNINDENT .UNINDENT .sp For branching on more than one case, try cond: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv somevar 33) (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 The macro \fB(when CONDITION THEN\-1 THEN\-2 …)\fP is shorthand for \fB(if CONDITION (do THEN\-1 THEN\-2 …))\fP\&. \fBunless\fP works the same as \fBwhen\fP, but inverts the condition with \fBnot\fP\&. .sp Hy\(aqs basic loops are while and for: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv x 3) (while (> x 0) (print x) (setv x (\- x 1))) ; => 3 2 1 (for [x [1 2 3]] (print x)) ; => 1 2 3 .ft P .fi .UNINDENT .UNINDENT .sp A more functional way to iterate is provided by the comprehension forms such as lfor\&. Whereas \fBfor\fP always returns \fBNone\fP, \fBlfor\fP returns a list with one element per iteration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (lfor x [1 2 3] (* x 2))) ; => [2, 4, 6] .ft P .fi .UNINDENT .UNINDENT .SS Functions, classes, and modules .sp Define named functions with defn: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn fib [n] (if (< n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) (print (fib 8)) ; => 21 .ft P .fi .UNINDENT .UNINDENT .sp Define anonymous functions with fn: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (list (filter (fn [x] (% x 2)) (range 10)))) ; => [1, 3, 5, 7, 9] .ft P .fi .UNINDENT .UNINDENT .sp Special symbols in the parameter list of \fBdefn\fP or \fBfn\fP allow you to indicate optional arguments, provide default values, and collect unlisted arguments: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn test [a b &optional c [d "x"] &rest e] [a b c d e]) (print (test 1 2)) ; => [1, 2, None, \(aqx\(aq, ()] (print (test 1 2 3 4 5 6 7)) ; => [1, 2, 3, 4, (5, 6, 7)] .ft P .fi .UNINDENT .UNINDENT .sp Set a function parameter by name with a \fB:keyword\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (test 1 2 :d "y") ; => [1, 2, None, \(aqy\(aq, ()] .ft P .fi .UNINDENT .UNINDENT .sp Define classes with defclass: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defclass FooBar [] (defn __init__ [self x] (setv self.x x)) (defn get\-x [self] self.x)) .ft P .fi .UNINDENT .UNINDENT .sp Here we create a new instance \fBfb\fP of \fBFooBar\fP and access its attributes by various means: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv fb (FooBar 15)) (print fb.x) ; => 15 (print (. fb x)) ; => 15 (print (.get\-x fb)) ; => 15 (print (fb.get\-x)) ; => 15 .ft P .fi .UNINDENT .UNINDENT .sp Note that syntax like \fBfb.x\fP and \fBfb.get\-x\fP only works when the object being invoked (\fBfb\fP, in this case) is a simple variable name. To get an attribute or call a method of an arbitrary form \fBFORM\fP, you must use the syntax \fB(. FORM x)\fP or \fB(.get\-x FORM)\fP\&. .sp Access an external module, whether written in Python or Hy, with import: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import math) (print (math.sqrt 2)) ; => 1.4142135623730951 .ft P .fi .UNINDENT .UNINDENT .sp Python can import a Hy module like any other module so long as Hy itself has been imported first, which, of course, must have already happened if you\(aqre running a Hy program. .SS Macros .sp Macros are the basic metaprogramming tool of Lisp. A macro is a function that is called at compile time (i.e., when a Hy program is being translated to Python \fI\%ast\fP objects) and returns code, which becomes part of the final program. Here\(aqs a simple example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "Executing") (defmacro m [] (print "Now for a slow computation") (setv x (% (** 10 10 7) 3)) (print "Done computing") x) (print "Value:" (m)) (print "Done executing") .ft P .fi .UNINDENT .UNINDENT .sp If you run this program twice in a row, you\(aqll see this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ hy example.hy Now for a slow computation Done computing Executing Value: 1 Done executing $ hy example.hy Executing Value: 1 Done executing .ft P .fi .UNINDENT .UNINDENT .sp The slow computation is performed while compiling the program on its first invocation. Only after the whole program is compiled does normal execution begin from the top, printing "Executing". When the program is called a second time, it is run from the previously compiled bytecode, which is equivalent to simply: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "Executing") (print "Value:" 1) (print "Done executing") .ft P .fi .UNINDENT .UNINDENT .sp Our macro \fBm\fP has an especially simple return value, an integer, which at compile\-time is converted to an integer literal. In general, macros can return arbitrary Hy forms to be executed as code. There are several special operators and macros that make it easy to construct forms programmatically, such as quote (\fB\(aq\fP), quasiquote (\fB\(ga\fP), unquote (\fB~\fP), and defmacro!\&. The previous chapter has a simple example of using \fB\(ga\fP and \fB~\fP to define a new control construct \fBdo\-while\fP\&. .sp Sometimes it\(aqs nice to be able to call a one\-parameter macro without parentheses. Tag macros allow this. The name of a tag macro is often just one character long, but since Hy allows most Unicode characters in the name of a macro (or ordinary variable), you won\(aqt out of characters soon. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (deftag ↻ [code] \&... (setv op (last code) params (list (butlast code))) \&... \(ga(~op ~@params)) => #↻(1 2 3 +) 6 .ft P .fi .UNINDENT .UNINDENT .sp What if you want to use a macro that\(aqs defined in a different module? \fBimport\fP won\(aqt help, because it merely translates to a Python \fBimport\fP statement that\(aqs executed at run\-time, and macros are expanded at compile\-time, that is, during the translation from Hy to Python. Instead, use require, which imports the module and makes macros available at compile\-time. \fBrequire\fP uses the same syntax as \fBimport\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (require tutorial.macros) => (tutorial.macros.rev (1 2 3 +)) 6 .ft P .fi .UNINDENT .UNINDENT .SS Next steps .sp You now know enough to be dangerous with Hy. You may now smile villainously and sneak off to your Hydeaway to do unspeakable things. .sp Refer to Python\(aqs documention for the details of Python semantics, and the rest of this manual for Hy\-specific features. Like Hy itself, the manual is incomplete, but contributions are always welcome. .SH HY STYLE GUIDE .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 interoperability. .SS Layout & Indentation .sp The #1 complaint about Lisp? .INDENT 0.0 .INDENT 3.5 \fIIt\(aqs too weird looking with all those parentheses! How do you even\fP \fBread\fP \fIthat?\fP .UNINDENT .UNINDENT .sp And, they\(aqre right! Lisp was originally much too hard to read. Then they figured out layout and indentation. And it was glorious. .SS The Three Laws .sp Here\(aqs the secret: \fIReal Lispers don\(aqt count the brackets.\fP They fade into the background. When reading Lisp, disregard the trailing closing brackets\-\-\-those are for the computer, not the human. As in Python, read the code structure by indentation. .sp Lisp code is made of trees\-\-\-Abstract Syntax Trees\-\-\-not strings. S\-expressions are very direct textual representation of AST. That\(aqs the level of \fIhomoiconicity\fP\-\-\-the level Lisp macros operate on. It\(aqs not like the C\-preprocessor or Python\(aqs interpolated eval\-string tricks that see code as just letters. That\(aqs not how to think of Lisp code; think tree structure, not delimiters. .INDENT 0.0 .IP 1. 3 Closing brackets must NEVER be left alone, sad and lonesome on their own line. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ; Lots of Irritating Superfluous Parentheses ; L.I.S.P. ;)) ;; How the experienced Lisper sees it. Indented trees. Like Python. (defn fib [n (if (<= n 2 n (+ (fib (\- n 1 (fib (\- n 2 ;; BAD ;; We\(aqre trying to ignore them and you want to give them their own line? ;; Hysterically ridiculous. (defn fib [ n ] ; My eyes! (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))) ) ) ; GAH, BURN IT WITH FIRE! .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP 2. 3 New lines must ALWAYS be indented past their parent opening bracket. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED (foo (, arg1 arg2)) ;; BAD. And evil. ;; Same bracket structure as above, but not enough indent. (foo (, arg1 arg2)) ;; PREFERRED. Same indent as above, but now it matches the brackets. (fn [arg] arg) ;; Remember, when reading Lisp, you ignore the trailing brackets. ;; Look at what happens if we remove them. ;; Can you tell where they should go by the indentation? (foo (, arg1 arg2 (foo (, arg1 arg2 (fn [arg arg ;; See how the structure of those last two became indistinguishable? ;; Reconstruction of the bad example by indent. ;; Not what we started with, is it? (foo (, arg1) arg2) ;; Beware of brackets with reader syntax. ;; You still have to indent past them. ;; BAD \(ga#{(foo) ~@[(bar) 1 2]} ;; Above, no trail. \(ga#{(foo ~@[(bar 1 2 ;; Reconstruction. Is. Wrong. \(ga#{(foo)} ~@[(bar)] 1 2 ;; PREFERRED \(ga#{(foo) ~@[(bar) 1 2]} ;; OK ;; A string is an atom, not a HySequence. (foo "abc xyz") ;; Still readable without trailing brackets. (foo "abc xyz" ; Double\-quote isn\(aqt a closing bracket. Don\(aqt ignore it. .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP 3. 3 New lines must NEVER be indented past the previous element\(aqs opening bracket. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; BAD ((get\-fn q) x y) ;; The above with trailing brackets removed. See the problem? ((get\-fn q x y ;; By indentation, this is where the brackets should go. ((get\-fn q x y)) ;; OK ((get\-fn q) x y) ;; The above without trailing brackets. Still OK (for humans). ((get\-fn q) x ; The ) on this line isn\(aqt trailing! y ;; PREFERRED, since the ) should end the line. ((get\-fn q) x y) .ft P .fi .UNINDENT .UNINDENT .SS Limits .sp Follow PEP 8 rules for line limits, viz. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 72 columns max for text (docstrings and comments). .IP \(bu 2 79 columns max for other code, OR .IP \(bu 2 99 for other code if primarily maintained by a team that can agree to 99. .UNINDENT .UNINDENT .UNINDENT .SS Whitespace .sp AVOID trailing spaces. They suck! .sp AVOID tabs in code. Indent with spaces only. .sp PREFER the \fB\et\fP escape sequence to literal tab characters in one\-line string literals. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Literal tabs are OK inside multiline strings if you also add a warning comment. .IP \(bu 2 But \fB\et\fP is still PREFERRED in multiline strings. .IP \(bu 2 The comment should PREFERABLY appear just before the string. .IP \(bu 2 But a blanket warning at the top of a function, class, or file is OK. .UNINDENT .UNINDENT .UNINDENT .SS Alignment .sp Line up arguments to function calls when splitting over multiple lines. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 The first argument PREFERABLY stays on the first line with the function name, .IP \(bu 2 but may instead start on the next line indented one space past its parent bracket. .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED. All args aligned with first arg. (foofunction arg1 (barfunction bararg1 bararg2 bararg3) ; Aligned with bararg1. arg3) ;; BAD (foofunction arg1 (barfunction bararg1 bararg2 ; Wrong. Looks like a macro body. bararg3) ; Why?! arg3) ;; PREFERRED. Args can all go on one line if it fits. (foofunction arg1 (barfunction bararg1 bararg2 bararg3) arg3) ;; OK. Args not on first line, but still aligned. (foofunction arg1 ; Indented one column past parent ( (barfunction bararg1 ; Indent again. bararg2 ; Aligned with bararg1. bararg3) arg3) ; Aligned with arg1. .ft P .fi .UNINDENT .UNINDENT .SS Hold it Open .sp If you need to separate a bracket trail use a \fB#_ /\fP comment to hold it open. This avoids violating law #1. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED [(foo) (bar) (baz)] ;; OK, especially if the list is long. (Not that three is long.) ;; This is better for version control line diffs. [ ; Opening brackets can\(aqt be "trailing closing brackets" btw. (foo) (bar) (baz) #_ /] ; Nothing to see here. Move along. ;; Examples of commenting out items at the end of a list follow. ;; As with typing things in the REPL, these cases are less important ;; if you\(aqre the only one that sees them. But even so, maintaining ;; good style can help prevent errors. ;; BAD and a syntax error. Lost a bracket. [(foo) ;; (bar) ;; (baz)] ;; BAD. Broke law #1. [(foo) ;; (bar) ;; (baz) ] ;; PREFERRED ;; The discard syntax respects code structure, ;; so it\(aqs less likely to cause errors. [(foo) #_(bar) #_(baz)] ;; OK. Adding a final discarded element makes line comments safer. [(foo) ;; (bar) ;; (baz) #_ /] .ft P .fi .UNINDENT .UNINDENT .SS Snuggle .sp Brackets like to snuggle, don\(aqt leave them out in the cold! .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED [1 2 3] (foo (bar 2)) ;; BAD [ 1 2 3 ] ( foo ( bar 2 ) ) ;; BAD. And ugly. [ 1 2 3] (foo( bar 2) ) .ft P .fi .UNINDENT .UNINDENT .SS Grouping .sp Use whitespace to show implicit groups, but be consistent within a form. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; Older Lisps would typically wrap such groups in even more parentheses. ;; (The Common Lisp LOOP macro was a notable exception.) ;; But Hy takes after Clojure, which has a lighter touch. ;; BAD. Can\(aqt tell key from value without counting {1 9 2 8 3 7 4 6 5 5} ;; PREFERRED. This can fit on one line. Clojure would have used commas ;; here, but those aren\(aqt whitespace in Hy. Use extra spaces instead. {1 9 2 8 3 7 4 6 5 5} ;; OK. And preferred if it couldn\(aqt fit on one line. {1 9 2 8 3 7 4 6 5 5} ; Newlines show key\-value pairs in dict. ;; BAD ;; This grouping makes no sense. #{1 2 3 4} ; It\(aqs a set, so why are there pairs? ;; BAD ;; This grouping also makes no sense. But, it could be OK in a macro or ;; something if this grouping was somehow meaningful there. [1 1 2 1 2 3] ; wHy do you like random patterns? [sic pun, sorry] ;; Be consistent. Separate all groups the same way in a form. ;; BAD {1 9 2 8 3 7 4 6 5 5} ; Pick one or the other! ;; BAD {1 9 2 8 3 7 4 6 5 5} ; You forgot something. ;; Groups of one must also be consistent. ;; PREFERRED (foo 1 2 3) ; No need for extra spaces here. ;; OK, but you could have fit this on one line. (foo 1 2 3) ;; OK, but you still could have fit this on one line. [1 2] ;; BAD (foo 1 2 ; This isn\(aqt a pair? 3) ; Lines or spaces\-\-pick one or the other! ;; PREFERRRED (foofunction (make\-arg) (get\-arg) #tag(do\-stuff) ; Tags belong with what they tag. #* args ; #* goes with what it unpacks. :foo spam :bar eggs ; Keyword args are also pairs. Group them. #** kwargs) ;; PREFERRED. Spaces divide groups on one line. (quux :foo spam :bar eggs #* with\-spam) {:foo spam :bar eggs} ;; OK. The colon is still enough to indicate groups. (quux :foo spam :bar eggs #* with\-spam) {:foo spam :bar eggs} ;; OK. ("foo" spam "bar" eggs} ;; BAD. Can\(aqt tell key from value. (quux :foo :spam :bar :eggs :baz :bacon) {:foo :spam :bar :eggs :baz :bacon} {"foo" "spam" "bar" "eggs" "baz" "bacon"} ;; PREFERRED (quux :foo :spam :bar :eggs :baz :bacon) {:foo :spam :bar :eggs :baz :bacon} {"foo" "spam" "bar" "eggs" "baz" "bacon"} ;; OK. Yep, those are pairs too. (setv x 1 y 2) ;; PREFERRED. This fits on one line. (setv x 1 y 2) ;; BAD. Doesn\(aqt separate groups. (print (if (< n 0.0) "negative" (= n 0.0) "zero" (> n 0.0) "positive" "not a number")) ;; BAD. And evil. Broke law #3. Shows groups but args aren\(aqt aligned. (print (if (< n 0.0) "negative" (= n 0.0) "zero" (> n 0.0) "positive" "not a number")) ;; BAD. Shows groups but args aren\(aqt aligned. ;; If the then\-parts weren\(aqt atoms, this would break law #3. (print (if (< n 0.0) "negative" (= n 0.0) "zero" (> n 0.0) "positive" "not a number")) ;; OK. Redundant (do) forms allow extra indent to show groups ;; without violating law #3. (print (if (< n 0.0) (do "negative") (= n 0.0) (do "zero") (> n 0.0) (do "positive") "not a number")) .ft P .fi .UNINDENT .UNINDENT .sp Separate toplevel forms (including toplevel comments not about a particular form) with a single blank line, rather than two as in Python. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 This can be omitted for tightly associated forms. .UNINDENT .UNINDENT .UNINDENT .sp Methods within a defclass need not be separated by blank line. .SS Special Arguments .sp Macros and special forms are normally indented one space past the parent bracket, but can also have "special" arguments that are indented like function arguments. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Macros with an \fB&rest body\fP argument contain an implicit \fBdo\fP\&. .IP \(bu 2 The body is never special, but the arguments before it are. .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED (assoc foo ; foo is special "x" 1 ; remaining args are not special. Indent 2 spaces. "y" 2) ;; PREFERRED ;; The do form has no special args. Indent like a function call. (do (foo) (bar) (baz)) ;; OK ;; No special args to distinguish. This is also valid function indent. (do (foo) (bar) (baz)) ;; PREFERRED (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; OK (defn fib [n] ; name and argslist are special. Indent like function args. ;; The defn body is not special. Indent 1 space past parent bracket. (if (<= n 2) n (+ (fib (\- n 1)) ; Emacs\-style else indent. (fib (\- n 2))))) .ft P .fi .UNINDENT .UNINDENT .SS Removing Whitespace .sp Removing whitespace can also make groups clearer. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; lookups ;; OK (. foo ["bar"]) ;; PREFERRED (. foo["bar"]) ;; BAD. Doesn\(aqt show groups clearly. (import foo foo [spam :as sp eggs :as eg] bar bar [bacon]) ;; OK. Extra spaces show groups. (import foo foo [spam :as sp eggs :as eg] bar bar [bacon]) ;; PREFERRED. Removing spaces is even clearer. (import foo foo[spam :as sp eggs :as eg] bar bar[bacon]) ;; OK. Newlines show groups. (import foo foo [spam :as sp eggs :as eg] bar bar [bacon]) ;; PREFERRED, It\(aqs more consistent with the preferred one\-line version. (import foo foo[spam :as sp eggs :as eg] bar bar[bacon]) ;; Avoid whitespace after tags. ;; Note which shows groups better. ;; BAD (foofunction #tag "foo" #tag (foo) #* (get\-args)) ;; OK (foofunction #tag "foo" #tag (foo) #* (get\-args)) ;; PREFERRED (foofunction #tag"foo" #tag(foo) #*(get\-args)) ;; PREFERRED ;; Can\(aqt group these by removing whitespace. Use extra spaces instead. (foofunction #x foo #x bar #* args) ;; OK ;; Same idea, but this could have fit on one line. (foofunction #x foo #x bar #* args) ;; OK, but you don\(aqt need to separate function name from first arg. (foofunction #x foo #x bar #* args) ;; OK. But same idea. ;; No need to separate the first group from the function name. (foofunction #x foo #x bar #* args) ;; PREFERRED. It\(aqs still clear what this is tagging. ;; And you don\(aqt have to re\-indent. #_ (def foo [] stuff) ;; OK, but more work. #_(def foo [] stuff) ;; BAD, you messed up the indent and broke law #2. #_(def foo [] stuff) ;; BAD, keep the tag grouped with its argument. #_ (def foo [] stuff) .ft P .fi .UNINDENT .UNINDENT .SS Close Bracket, Close Line .sp A \fIsingle\fP closing bracket SHOULD end the line, unless it\(aqs in the middle of an implicit group. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 If the forms are small and simple you can maybe leave them on one line. .UNINDENT .UNINDENT .UNINDENT .sp A \fItrain\fP of closing brackets MUST end the line. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; One\-liners are overrated. ;; Maybe OK if you\(aqre just typing into the REPL. ;; But even then, maintaining good style can help prevent errors. ;; BAD. One\-liner is too hard to read. (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; BAD. Getting better, but the first line is still too complex. (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) (fib (\- n 2))))) ;; OK. Barely. (defn fib [n] (if (<= n 2) n (+ (fib (\- n 1)) ; This line is pushing it. (fib (\- n 2))))) ;; OK (defn fib [n] ; Saw a "]", newline. (if (<= n 2) ; OK to break here, since there\(aqs only one pair. n (+ (fib (\- n 1)) ; Whitespace separation (Emacs else\-indent). (fib (\- n 2))))) ;; OK (defn fib [n] ; Saw a "]", end line. (Margin comments don\(aqt count.) (if (<= n 2) n ; Saw a ")", but it\(aqs in a pair starting in this line. (+ (fib (\- n 1)) ; Saw a "))" MUST end line. (fib (\- n 2))))) ;; OK. Pairs. (print (if (< n 0.0) "negative" ; Single ) inside group. No break. (= n 0.0) "zero" (> n 0.0) "positive" :else "not a number")) ; :else is not magic; True works too. ;; OK. Avoided line breaks at single ) to show pairs. (print (if (< n 0.0) "negative" (= n 0.0) "zero" (> n 0.0) (do (do\-foo) ; Single ) inside group. No break. (do\-bar) "positive") "not a number")) ; Implicit else is PREFERRED. ;; BAD (print (if (< n 0.0) "negative" (= n 0.0) "zero" (and (even? n) (> n 0.0)) "even\-positive" ; Bad. "))" must break. (> n 0.0) "positive" "not a number")) ;; BAD (print (if (< n 0.0) "negative" (= n 0.0) "zero" (and (even? n) (> n 0.0)) (do (do\-foo) ; Y U no break? (do\-bar) "even\-positive") (> n 0.0) "positive" "not a number")) ;; OK. Blank line separates multiline groups. (print (if (< n 0.0) "negative" (= n 0.0) "zero" (and (even? n) (> n 0.0)) (do (do\-foo) (do\-bar) "even\-positive") (> n 0.0) "positive" "not a number")) ;; BAD. Groups are not separated consistently. (print (if (< n 0.0) "negative" (= n 0.0) "zero" (> n 0.0) (do (do\-foo) "positive") "not a number")) ;; OK. Single )\(aqs and forms are simple enough. (with [f (open "names.txt")] (\-> (.read f) .strip (.replace "\e"" "") (.split ",") sorted))) ;; PREFERRED. Even so, this version is much clearer. (with [f (open "names.txt")] (\-> (.read f) .strip (.replace "\e"" "") (.split ",") sorted))) .ft P .fi .UNINDENT .UNINDENT .SS Comments .sp Prefer docstrings to comments where applicable\-\-\-in \fBfn\fP, \fBdefclass\fP, at the top of the module, and in any other macros derived from these that can take a docstring (e.g. \fBdefmacro/g!\fP, \fBdeftag\fP, \fBdefn\fP). .sp Docstrings contents follow the same conventions as Python. .sp The \fB(comment)\fP macro is still subject to the three laws. If you\(aqre tempted to violate them, consider discarding a string instead with \fB#_\fP\&. .sp Semicolon comments always have one space between the semicolon and the start of the comment. Also, try to not comment the obvious. .sp Comments with more than a single word should start with a capital letter and use punctuation. .sp Separate sentences with a single space. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; This commentary is not about a particular form. ;; These can span multiple lines. Limit them to column 72, per PEP 8. ;; Separate them from the next form or form comment with a blank line. ;; PREFERRED. (setv ind (dec x)) ; Indexing starts from 0, ; margin comment continues on new line. ;; OK ;; 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 ;; Comment about the whole foofunction call. ;; These can also span mulitple lines. (foofunction ;; Form comment about (get\-arg1). Not a margin comment! (get\-arg1) ;; Form comment about arg2. The indent matches. arg2) .ft P .fi .UNINDENT .UNINDENT .sp Indent form comments at the same level as the form they\(aqre commenting about; they must always start with exactly two semicolons \fB;;\fP\&. Form comments appear directly above what they\(aqre commenting on, never below. .sp General toplevel commentary is not indented; these must always start with exactly two semicolons \fB;;\fP and be separated from the next form with a blank line. For long commentary, consider using a \fB#_\fP applied to a string for this purpose instead. .sp Margin comments start two spaces from the end of the code; they must always start with a single semicolon \fB;\fP\&. Margin comments may be continued on the next line. .sp When commenting out entire forms, prefer the \fB#_\fP syntax. But if you do need line comments, use the more general double\-colon form. .SS Coding Style .SS Pythonic Names .sp Use Python\(aqs naming conventions where still applicable to Hy. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 The first parameter of a method is \fBself\fP, .IP \(bu 2 of a classmethod is \fBcls\fP\&. .UNINDENT .UNINDENT .UNINDENT .SS Threading Macros .sp PREFER 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 0.0 .INDENT 3.5 .sp .nf .ft C ;; BAD. Not wrong, but could be much clearer with a threading macro. (setv NAMES (with [f (open "names.txt")] (sorted (.split (.replace (.strip (.read f)) "\e"" "") ",")))) ;; PREFERRED. This compiles exactly the same way as the above. (setv NAMES (with [f (open "names.txt")] (\-> (.read f) .strip (.replace "\e"" "") (.split ",") sorted))) ;; BAD. Probably. The macro makes it less clear in this case. (defn square? [x] (\->> 2 (pow (int (sqrt x))) (= x))) ;; OK. Much clearer that the previous example above. (defn square? [x] (\-> x sqrt int (pow 2) (= x)) ;; PREFERRED. Judicious use. ;; You don\(aqt have to thread everything if it improves clarity. (defn square? [x] (= x (\-> x sqrt int (pow 2)))) ;; OK. Still clear enough with no threading macro this time. (defn square? [x] (= x (pow (int (sqrt x)) ; saw a "))", break. 2)) ; aligned with first arg to pow .ft P .fi .UNINDENT .UNINDENT .SS Method Calls .sp Clojure\-style dot notation is PREFERRED over the direct call of the object\(aqs method, though both will continue to be supported. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED (with [fd (open "/etc/passwd")] (print (.readlines fd))) ;; OK (with [fd (open "/etc/passwd")] (print (fd.readlines))) .ft P .fi .UNINDENT .UNINDENT .SS Use More Arguments .sp PREFER using multiple arguments to multiple forms. But judicious use of redundant forms can clarify intent. AVOID the separating blank line for toplevel forms in this case. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; BAD (setv x 1) (setv y 2) (setv z 3) (setv foo 9) (setv bar 10) ;; OK (setv x 1 y 2 z 3 foo 9 bar 10) ;; PREFERRED (setv x 1 y 2 z 3) (setv foo 9 bar 10) .ft P .fi .UNINDENT .UNINDENT .SS Imports .sp As in Python, group imports. .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Standard library imports (including Hy\(aqs) first. .IP \(bu 2 Then third\-party modules, .IP \(bu 2 and finally internal modules. .UNINDENT .UNINDENT .UNINDENT .sp PREFER one import form for each group. .sp PREFER alphabetical order within groups. .sp Require macros before any imports and group them the same way. .sp But sometimes imports are conditional or must be ordered a certain way for programmatic reasons, which is OK. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; PREFERRED (require hy.extra.anaphoric [%]) (require thirdparty [some\-macro]) (require mymacros [my\-macro]) (import json re) (import numpy :as np pandas :as pd) (import mymodule1) .ft P .fi .UNINDENT .UNINDENT .SS Underscores .sp Prefer hyphens when separating words. .INDENT 0.0 .IP \(bu 2 PREFERRED \fBfoo\-bar\fP .IP \(bu 2 BAD \fBfoo_bar\fP .UNINDENT .sp Don\(aqt use leading hyphens, except for "operators" or symbols meant to be read as including one, e.g. \fB\-Inf\fP, \fB\->foo\fP\&. .sp Prefix private names with an underscore, not a dash. to avoid confusion with negated literals like \fB\-Inf\fP, \fB\-42\fP or \fB\-4/2\fP\&. .INDENT 0.0 .IP \(bu 2 PREFERRED \fB_x\fP .IP \(bu 2 BAD \fB\-x\fP .UNINDENT .sp Write Python\(aqs magic "dunder" names the same as in Python. Like \fB__init__\fP, not \fB\-\-init\-\-\fP or otherwise, to be consistent with the private names rule above. .sp Private names should still separate words using dashes instead of underscores, to be consistent with non\-private parameter names and such that need the same name sans prefix, like \fBfoo\-bar\fP, not \fBfoo_bar\fP\&. .INDENT 0.0 .IP \(bu 2 PREFERRED \fB_foo\-bar\fP .IP \(bu 2 BAD \fB_foo_bar\fP .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; BAD ;; What are you doing? (_= spam 2) ; Throwing it away? (_ 100 7) ; i18n? ;; PREFERRED ;; Clearly subtraction. (\-= spam 2) (\- 100 7) ;; BAD ;; This looks weird. (_>> foo bar baz) ;; PREFERRED ;; OH, it\(aqs an arrow! (\->> foo bar baz) ;; Negative x? (setv \-x 100) ; BAD. Unless you really meant that? ;; PREFERRED ;; Oh, it\(aqs just a module private. (setv _x 100) ;; BAD (class Foo [] (defn __init\-\- [self] ...)) ;; OK (class Foo [] ;; Less weird? (defn \-\-init\-\- [self] ...)) ;; PREFERRED (class Foo [] (defn __init__ [self] ...)) ;; OK, but would be module private. (No import *) (def \->dict [&rest pairs] (dict (partition pairs))) .ft P .fi .UNINDENT .UNINDENT .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 .IP \(bu 2 \fI\%Parinfer\fP and \fI\%Parlinter\fP (the three laws) .IP \(bu 2 The Community Scheme Wiki \fI\%scheme\-style\fP (ending bracket ends the line) .IP \(bu 2 \fI\%Riastradh\(aqs Lisp Style Rules\fP (Lisp programmers do not ... Azathoth forbid, count brackets) .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.11.0. .UNINDENT .INDENT 0.0 .TP .B \-\-spy Print equivalent Python code before executing in REPL. 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 \fI\-\-spy\fP only works on REPL mode. \&.. versionadded:: 0.9.11 .UNINDENT .INDENT 0.0 .TP .B \-\-repl\-output\-fn Format REPL output using specific function (e.g., hy.contrib.hy\-repr.hy\-repr) .sp New in version 0.13.0. .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 <\-> Python interop .sp Despite being a Lisp, Hy aims to be fully compatible with Python. That means every Python module or package can be imported in Hy code, and vice versa. .sp Mangling allows variable names to be spelled differently in Hy and Python. For example, Python\(aqs \fBstr.format_map\fP can be written \fBstr.format\-map\fP in Hy, and a Hy function named \fBvalid?\fP would be called \fBis_valid\fP in Python. In Python, you can import Hy\(aqs core functions \fBmangle\fP and \fBunmangle\fP directly from the \fBhy\fP package. .SS Using Python from Hy .sp You can embed Python code directly into a Hy program with the special operators py\-specialform and pys\-specialform\&. .sp Using a Python module from Hy is nice and easy: you just have to import it. If you have the following in \fBgreetings.py\fP in Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def greet(name): print("hello," 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") ; prints "hello, foo" .ft P .fi .UNINDENT .UNINDENT .sp You can also import \fB\&.pyc\fP bytecode files, of course. .SS Using Hy from Python .sp Suppose you have written some useful utilities in Hy, and you want to use them in regular Python, or to share them with others as a package. Or suppose you work with somebody else, who doesn\(aqt like Hy (!), and only uses Python. .sp In any case, you need to know how to use Hy from Python. Fear not, for it is easy. .sp If you save the following in \fBgreetings.hy\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv this\-will\-have\-underscores "See?") (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") # prints "Hello from Hy, Foo" print(greetings.this_will_have_underscores) # prints "See?" .ft P .fi .UNINDENT .UNINDENT .sp If you create a package with Hy code, and you do the \fBimport hy\fP in \fB__init__.py\fP, you can then directly include the package. Of course, Hy still has to be installed. .SS Compiled files .sp You can also compile a module with \fBhyc\fP, which gives you a \fB\&.pyc\fP file. You can import that file. Hy does not \fIreally\fP need to be installed ; however, if in your code, you use any symbol from core, a corresponding \fBimport\fP statement will be generated, and Hy will have to be installed. .sp Even if you do not use a Hy builtin, but just another function or variable with the name of a Hy builtin, the \fBimport\fP will be generated. For example, the previous code causes the import of \fBname\fP from \fBhy.core.language\fP\&. .sp \fBBottom line: in most cases, Hy has to be installed.\fP .SS Launching a Hy REPL from Python .sp You can use the function \fBrun_repl()\fP to launch the Hy REPL from Python: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> import hy.cmdline >>> hy.cmdline.run_repl() hy 0.12.1 using CPython(default) 3.6.0 on Linux => (defn foo [] (print "bar")) => (test) bar .ft P .fi .UNINDENT .UNINDENT .sp If you want to print the Python code Hy generates for you, use the \fBspy\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> import hy.cmdline >>> hy.cmdline.run_repl(spy=True) hy 0.12.1 using CPython(default) 3.6.0 on Linux => (defn test [] (print "bar")) def test(): return print(\(aqbar\(aq) => (test) test() bar .ft P .fi .UNINDENT .UNINDENT .SS Evaluating strings of Hy code from Python .sp Evaluating a string (or \fBfile\fP object) containing a Hy expression requires two separate steps. First, use the \fBread_str\fP function (or \fBread\fP for a \fBfile\fP object) to turn the expression into a Hy model: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> import hy >>> expr = hy.read_str("(\- (/ (+ 1 3 88) 2) 8)") .ft P .fi .UNINDENT .UNINDENT .sp Then, use the \fBeval\fP function to evaluate it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> hy.eval(expr) 38.0 .ft P .fi .UNINDENT .UNINDENT .SS Syntax .SS identifiers .sp An identifier consists of a nonempty sequence of Unicode characters that are not whitespace nor any of the following: \fB( ) [ ] { } \(aq "\fP\&. Hy first tries to parse each identifier into a numeric literal, then into a keyword if that fails, and finally into a symbol if that fails. .SS numeric literals .sp In addition to regular numbers, standard notation from Python for non\-base 10 integers is used. \fB0x\fP for Hex, \fB0o\fP for Octal, \fB0b\fP for Binary. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print 0x80 0b11101 0o102 30) .ft P .fi .UNINDENT .UNINDENT .sp Underscores and commas can appear anywhere in a numeric literal except the very beginning. They have no effect on the value of the literal, but they\(aqre useful for visually separating digits. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print 10,000,000,000 10_000_000_000) .ft P .fi .UNINDENT .UNINDENT .sp Unlike Python, Hy provides literal forms for NaN and infinity: \fBNaN\fP, \fBInf\fP, and \fB\-Inf\fP\&. .SS string literals .sp Hy allows double\-quoted strings (e.g., \fB"hello"\fP), but not single\-quoted strings like Python. The single\-quote character \fB\(aq\fP is reserved for preventing the evaluation of a form (e.g., \fB\(aq(+ 1 1)\fP), as in most Lisps. .sp Python\(aqs so\-called triple\-quoted strings (e.g., \fB\(aq\(aq\(aqhello\(aq\(aq\(aq\fP and \fB"""hello"""\fP) aren\(aqt supported. However, in Hy, unlike Python, any string literal can contain newlines. Furthermore, Hy supports an alternative form of string literal called a "bracket string" similar to Lua\(aqs long brackets. Bracket strings have customizable delimiters, like the here\-documents of other languages. A bracket string begins with \fB#[FOO[\fP and ends with \fB]FOO]\fP, where \fBFOO\fP is any string not containing \fB[\fP or \fB]\fP, including the empty string. (If \fBFOO\fP is exactly \fBf\fP or begins with \fBf\-\fP, the bracket string is interpreted as a \fI\%format string\fP\&.) For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (print #[["That\(aqs very kind of yuo [sic]" Tom wrote back.]]) "That\(aqs very kind of yuo [sic]" Tom wrote back. => (print #[==[1 + 1 = 2]==]) 1 + 1 = 2 .ft P .fi .UNINDENT .UNINDENT .sp A bracket string can contain newlines, but if it begins with one, the newline is removed, so you can begin the content of a bracket string on the line following the opening delimiter with no effect on the content. Any leading newlines past the first are preserved. .sp Plain string literals support \fI\%a variety of backslash escapes\fP\&. To create a "raw string" that interprets all backslashes literally, prefix the string with \fBr\fP, as in \fBr"slash\enot"\fP\&. Bracket strings are always raw strings and don\(aqt allow the \fBr\fP prefix. .sp Like Python, Hy treats all string literals as sequences of Unicode characters by default. You may prefix a plain string literal (but not a bracket string) with \fBb\fP to treat it as a sequence of bytes. .sp Unlike Python, Hy only recognizes string prefixes (\fBr\fP, etc.) in lowercase. .SS format strings .sp A format string (or "f\-string", or "formatted string literal") is a string literal with embedded code, possibly accompanied by formatting commands. Hy f\-strings work much like \fI\%Python f\-strings\fP except that the embedded code is in Hy rather than Python, and they\(aqre supported on all versions of Python. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (print f"The sum is {(+ 1 1)}.") The sum is 2. .ft P .fi .UNINDENT .UNINDENT .sp Since \fB!\fP and \fB:\fP are identifier characters in Hy, Hy decides where the code in a replacement field ends, and any conversion or format specifier begins, by parsing exactly one form. You can use \fBdo\fP to combine several forms into one, as usual. Whitespace may be necessary to terminate the form: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv foo "a") => (print f"{foo:x<5}") … NameError: name \(aqhyx_fooXcolonXxXlessHthan_signX5\(aq is not defined => (print f"{foo :x<5}") axxxx .ft P .fi .UNINDENT .UNINDENT .sp Unlike Python, whitespace is allowed between a conversion and a format specifier. .sp Also unlike Python, comments and backslashes are allowed in replacement fields. Hy\(aqs lexer will still process the whole format string normally, like any other string, before any replacement fields are considered, so you may need to backslash your backslashes, and you can\(aqt comment out a closing brace or the string delimiter. .SS keywords .sp An identifier headed by a colon, such as \fB:foo\fP, is a keyword. If a literal keyword appears in a function call, it\(aqs used to indicate a keyword argument rather than passed in as a value. For example, \fB(f :foo 3)\fP calls the function \fBf\fP with the keyword argument named \fBfoo\fP set to \fB3\fP\&. Hence, trying to call a function on a literal keyword may fail: \fB(f :foo)\fP yields the error \fBKeyword argument :foo needs a value\fP\&. To avoid this, you can quote the keyword, as in \fB(f \(aq:foo)\fP, or use it as the value of another keyword argument, as in \fB(f :arg :foo)\fP\&. .sp Keywords can be called like functions as shorthand for \fBget\fP\&. \fB(:foo obj)\fP is equivalent to \fB(get obj :foo)\fP\&. An optional \fBdefault\fP argument is also allowed: \fB(:foo obj 2)\fP or \fB(:foo obj :default 2)\fP returns \fB2\fP if \fB(get obj :foo)\fP raises a \fBKeyError\fP\&. .SS symbols .sp Symbols are identifiers that are neither legal numeric literals nor legal keywords. In most contexts, symbols are compiled to Python variable names. Some example symbols are \fBhello\fP, \fB+++\fP, \fB3fiddy\fP, \fB$40\fP, \fBjust✈wrong\fP, and \fB🦑\fP\&. .sp Since the rules for Hy symbols are much more permissive than the rules for Python identifiers, Hy uses a mangling algorithm to convert its own names to Python\-legal names. The rules are: .INDENT 0.0 .IP \(bu 2 Convert all hyphens (\fB\-\fP) to underscores (\fB_\fP). Thus, \fBfoo\-bar\fP becomes \fBfoo_bar\fP\&. .IP \(bu 2 If the name ends with \fB?\fP, remove it and prepend \fBis_\fP\&. Thus, \fBtasty?\fP becomes \fBis_tasty\fP\&. .IP \(bu 2 If the name still isn\(aqt Python\-legal, make the following changes. A name could be Python\-illegal because it contains a character that\(aqs never legal in a Python name, it contains a character that\(aqs illegal in that position, or it\(aqs equal to a Python reserved word. .INDENT 2.0 .IP \(bu 2 Prepend \fBhyx_\fP to the name. .IP \(bu 2 Replace each illegal character with \fBXfooX\fP, where \fBfoo\fP is the Unicode character name in lowercase, with spaces replaced by underscores and hyphens replaced by \fBH\fP\&. Replace \fBX\fP itself the same way. If the character doesn\(aqt have a name, use \fBU\fP followed by its code point in lowercase hexadecimal. .UNINDENT .sp Thus, \fBgreen☘\fP becomes \fBhyx_greenXshamrockX\fP and \fBif\fP becomes \fBhyx_if\fP\&. .IP \(bu 2 Finally, any added \fBhyx_\fP or \fBis_\fP is added after any leading underscores, because leading underscores have special significance to Python. Thus, \fB_tasty?\fP becomes \fB_is_tasty\fP instead of \fBis__tasty\fP\&. .UNINDENT .sp Mangling isn\(aqt something you should have to think about often, but you may see mangled names in error messages, the output of \fBhy2py\fP, etc. A catch to be aware of is that mangling, as well as the inverse "unmangling" operation offered by the \fBunmangle\fP function, isn\(aqt one\-to\-one. Two different symbols can mangle to the same string and hence compile to the same Python variable. The chief practical consequence of this is that \fB\-\fP and \fB_\fP are interchangeable in all symbol names, so you shouldn\(aqt assign to the one\-character name \fB_\fP , or else you\(aqll interfere with certain uses of subtraction. .SS discard prefix .sp Hy supports the Extensible Data Notation discard prefix, like Clojure. Any form prefixed with \fB#_\fP is discarded instead of compiled. This completely removes the form so it doesn\(aqt evaluate to anything, not even None. It\(aqs often more useful than linewise comments for commenting out a form, because it respects code structure even when part of another form is on the same line. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (print "Hy" "cruel" "World!") Hy cruel World! => (print "Hy" #_"cruel" "World!") Hy World! => (+ 1 1 (print "Math is hard!")) Math is hard! Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: \(aqint\(aq and \(aqNoneType\(aq => (+ 1 1 #_(print "Math is hard!")) 2 .ft P .fi .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 The \fB^\fP symbol is used to denote annotations in three different contexts: .INDENT 0.0 .IP \(bu 2 Standalone variable annotations. .IP \(bu 2 Variable annotations in a setv call. .IP \(bu 2 Function argument annotations. .UNINDENT .sp They implement \fI\%PEP 526\fP and \fI\%PEP 3107\fP\&. .sp Here is some example syntax of all three usages: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ; Annotate the variable x as an int (equivalent to \(gax: int\(ga). (^int x) ; Can annotate with expressions if needed (equivalent to \(gay: f(x)\(ga). (^(f x) y) ; Annotations with an assignment: each annotation (int, str) covers the term that ; immediately follows. ; Equivalent to: x: int = 1; y = 2; z: str = 3 (setv ^int x 1 y 2 ^str z 3) ; Annotate a as an int, c as an int, and b as a str. ; Equivalent to: def func(a: int, b: str = None, c: int = 1): ... (defn func [^int a &optional ^str b ^int [c 1]] ...) .ft P .fi .UNINDENT .UNINDENT .sp The rules are: .INDENT 0.0 .IP \(bu 2 The value to annotate with is the value that immediately follows the caret. .IP \(bu 2 There must be no space between the caret and the value to annotate, otherwise it will be interpreted as a bitwise XOR like the Python operator. .IP \(bu 2 The annotation always comes (and is evaluated) \fIbefore\fP the value being annotated. This is unlike Python, where it comes and is evaluated \fIafter\fP the value being annotated. .UNINDENT .sp Note that variable annotations are only supported on Python 3.6+. .sp For annotating items with generic types, the \fI\%of\fP macro will likely be of use. .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 raise a compilation error. .sp Access to unknown attributes raises an \fI\%AttributeError\fP\&. Access to unknown keys raises an \fI\%IndexError\fP (on lists and tuples) or a \fI\%KeyError\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 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 as\-> .sp New in version 0.12.0. .sp Expands to sequence of assignments to the provided name, starting with head. The previous result is thus available in the subsequent form. Returns the final result, and leaves the name bound to it in the local scope. This behaves much like the other threading macros, but requires you to specify the threading point per form via the name instead of always the first or last argument. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ;; example how \-> and as\-> relate => (as\-> 0 it \&... (inc it) \&... (inc it)) 2 => (\-> 0 inc inc) 2 ;; create data for our cuttlefish database => (setv data [{:name "hooded cuttlefish" \&... :classification {:subgenus "Acanthosepion" \&... :species "Sepia prashadi"} \&... :discovered {:year 1936 \&... :name "Ronald Winckworth"}} \&... {:name "slender cuttlefish" \&... :classification {:subgenus "Doratosepion" \&... :species "Sepia braggi"} \&... :discovered {:year 1907 \&... :name "Sir Joseph Cooke Verco"}}]) ;; retrieve name of first entry => (as\-> (first data) it \&... (:name it)) \(aqhooded cuttlefish\(aq ;; retrieve species of first entry => (as\-> (first data) it \&... (:classification it) \&... (:species it)) \(aqSepia prashadi\(aq ;; find out who discovered slender cuttlefish => (as\-> (filter (fn [entry] (= (:name entry) \&... "slender cuttlefish")) data) it \&... (first it) \&... (:discovered it) \&... (:name it)) \(aqSir Joseph Cooke Verco\(aq ;; more convoluted example to load web page and retrieve data from it => (import [urllib.request [urlopen]]) => (as\-> (urlopen "http://docs.hylang.org/en/stable/") it \&... (.read it) \&... (.decode it "utf\-8") \&... (drop (.index it "Welcome") it) \&... (take 30 it) \&... (list it) \&... (.join "" it)) \(aqWelcome to Hy’s documentation! .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In these examples, the REPL will report a tuple (e.g. \fI(\(aqSepia prashadi\(aq, \(aqSepia prashadi\(aq)\fP) as the result, but only a single value is actually returned. .UNINDENT .UNINDENT .SS assert .sp \fBassert\fP is used to verify conditions while the program is running. If the condition is not met, an \fI\%AssertionError\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 \fI\%AssertionError\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 =>(do \&... (setv collection {}) \&... (assoc collection "Dog" "Bark") \&... (print collection)) {u\(aqDog\(aq: u\(aqBark\(aq} =>(do \&... (setv collection {}) \&... (assoc collection "Dog" "Bark" "Cat" "Meow") \&... (print collection)) {u\(aqCat\(aq: u\(aqMeow\(aq, u\(aqDog\(aq: u\(aqBark\(aq} =>(do \&... (setv 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 await .sp \fBawait\fP creates an \fI\%await expression\fP\&. It takes exactly one argument: the object to wait for. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import asyncio) => (defn/a main [] \&... (print "hello") \&... (await (asyncio.sleep 1)) \&... (print "world")) => (asyncio.run (main)) hello world .ft P .fi .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" (input "? ")) (break) (print "Try again"))) .ft P .fi .UNINDENT .UNINDENT .SS cmp .sp \fBcmp\fP creates a \fI\%comparison expression\fP\&. It isn\(aqt required for unchained comparisons, which have only one comparison operator, nor for chains of the same operator. For those cases, you can use the comparison operators directly with Hy\(aqs usual prefix syntax, as in \fB(= x 1)\fP or \fB(< 1 2 3)\fP\&. The use of \fBcmp\fP is to construct chains of heterogeneous operators, such as \fBx <= y < z\fP\&. It uses an infix syntax with the general form .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (cmp ARG OP ARG OP ARG…) .ft P .fi .UNINDENT .UNINDENT .sp Hence, \fB(cmp x <= y < z)\fP is equivalent to \fB(and (<= x y) (< y z))\fP, including short\-circuiting, except that \fBy\fP is only evaluated once. .sp Each \fBARG\fP is an arbitrary form, which does not itself use infix syntax. Use \fI\%py\fP if you want fully Python\-style operator syntax. You can also nest \fBcmp\fP forms, although this is rarely useful. Each \fBOP\fP is a literal comparison operator; other forms that resolve to a comparison operator are not allowed. .sp At least two \fBARG\fPs and one \fBOP\fP are required, and every \fBOP\fP must be followed by an \fBARG\fP\&. .sp As elsewhere in Hy, the equality operator is spelled \fB=\fP, not \fB==\fP as in Python. .SS comment .sp The \fBcomment\fP macro ignores its body and always expands to \fBNone\fP\&. Unlike linewise comments, the body of the \fBcomment\fP macro must be grammatically valid Hy, so the compiler can tell where the comment ends. Besides the semicolon linewise comments, Hy also has the \fB#_\fP discard prefix syntax to discard the next form. This is completely discarded and doesn\(aqt expand to anything, not even \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (print (comment

Surprise!

\&...

You\(aqd be surprised what\(aqs grammatically valid in Hy.

\&...

(Keep delimiters in balance, and you\(aqre mostly good to go.)

) \&... "Hy") None Hy => (print #_(comment

Surprise!

\&...

You\(aqd be surprised what\(aqs grammatically valid in Hy.

\&...

(Keep delimiters in balance, and you\(aqre mostly good to go.)

)) \&... "Hy") Hy .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 If only the condition is given in a branch, then the condition is also used as the result. The expansion of this single argument version is demonstrated below: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (cond [condition\-1] [condition\-2]) (if condition\-1 condition\-1 (if condition\-2 condition\-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] (side\-effect1 x) (if (% x 2) (continue)) (side\-effect2 x)) .ft P .fi .UNINDENT .UNINDENT .SS do .sp \fBdo\fP (called \fBprogn\fP in some Lisps) takes any number of forms, evaluates them, and returns the value of the last one, or \fBNone\fP if no forms were provided. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (+ 1 (do (setv x (+ 1 1)) x)) 3 .ft P .fi .UNINDENT .UNINDENT .SS doc / #doc .sp Documentation macro and tag macro. Gets help for macros or tag macros, respectively. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (doc doc) Help on function (doc) in module hy.core.macros: (doc)(symbol) macro documentation Gets help for a macro function available in this module. Use \(ga\(garequire\(ga\(ga to make other macros available. Use \(ga\(ga#doc foo\(ga\(ga instead for help with tag macro \(ga\(ga#foo\(ga\(ga. Use \(ga\(ga(help foo)\(ga\(ga instead for help with runtime objects. => (doc comment) Help on function (comment) in module hy.core.macros: (comment)(*body) Ignores body and always expands to None => #doc doc Help on function #doc in module hy.core.macros: #doc(symbol) tag macro documentation Gets help for a tag macro function available in this module. .ft P .fi .UNINDENT .UNINDENT .SS dfor .sp \fBdfor\fP creates a \fI\%dictionary comprehension\fP\&. Its syntax is the same as that of \fI\%lfor\fP except that the final value form must be a literal list of two elements, the first of which becomes each key and the second of which becomes each value. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (dfor x (range 5) [x (* x 10)]) {0: 0, 1: 10, 2: 20, 3: 30, 4: 40} .ft P .fi .UNINDENT .UNINDENT .SS setv .sp \fBsetv\fP is used to bind a value, object, or function to a symbol. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv 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 .sp You can provide more than one target–value pair, and the assignments will be made in order: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv x 1 y x x 2) (print x y) ; => 2 1 .ft P .fi .UNINDENT .UNINDENT .sp You can perform parallel assignments or unpack the source value with square brackets and \fI\%unpack\-iterable, unpack\-mapping\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv duo ["tim" "eric"]) (setv [guy1 guy2] duo) (print guy1 guy2) ; => tim eric (setv [letter1 letter2 #* others] "abcdefg") (print letter1 letter2 others) ; => a b [\(aqc\(aq, \(aqd\(aq, \(aqe\(aq, \(aqf\(aq, \(aqg\(aq] .ft P .fi .UNINDENT .UNINDENT .SS setx .sp Whereas \fBsetv\fP creates an assignment statement, \fBsetx\fP creates an assignment expression (see \fI\%PEP 572\fP). It requires Python 3.8 or later. Only one target–value pair is allowed, and the target must be a bare symbol, but the \fBsetx\fP form returns the assigned value instead of \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (when (> (setx x (+ 1 2)) 0) \&... (print x "is greater than 0")) 3 is greater than 0 .ft P .fi .UNINDENT .UNINDENT .SS defclass .sp New classes are declared with \fBdefclass\fP\&. It can take optional parameters in the following order: a list defining (a) possible super class(es) and a string (\fI\%docstring\fP). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defclass class\-name [super\-class\-1 super\-class\-2] "docstring" (setv attribute1 value1) (setv attribute2 value2) (defn method [self] (print "hello!"))) .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 [] \&... (setv age None) \&... (setv colour "white") \&... \&... (defn speak [self] (print "Meow"))) => (setv spot (Cat)) => (setv spot.colour "Black") \(aqBlack\(aq => (.speak spot) Meow .ft P .fi .UNINDENT .UNINDENT .SS defn .sp \fBdefn\fP is used to define functions. It requires two arguments: a name (given as a symbol) and a list of parameters (also given as symbols). Any remaining arguments constitute the body of the function. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn name [params] bodyform1 bodyform2...) .ft P .fi .UNINDENT .UNINDENT .sp If there at least two body forms, and the first of them is a string literal, this string becomes the \fI\%docstring\fP of the function. .sp Parameters may be prefixed with the following special symbols. If you use more than one, they can only appear in the given order (so all \fI&optional\fP parameters must precede any \fI&rest\fP parameter, \fI&rest\fP must precede \fI&kwonly\fP, and \fI&kwonly\fP must precede \fI&kwargs\fP). This is the same order that Python requires. .INDENT 0.0 .TP .B &optional All following parameters are optional. They may be given as two\-argument lists, where the first element is the parameter name and the second is the default value. The parameter can also be given as a single item, in which case the default value is \fBNone\fP\&. .sp The following example defines a function with one required positional argument as well as three optional arguments. The first optional argument defaults to \fBNone\fP and the latter two default to \fB"("\fP and \fB")"\fP, respectively. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (defn format\-pair [left\-val &optional right\-val [open\-text "("] [close\-text ")"]] \&... (+ open\-text (str left\-val) ", " (str right\-val) close\-text)) => (format\-pair 3) \(aq(3, None)\(aq => (format\-pair "A" "B") \(aq(A, B)\(aq => (format\-pair "A" "B" "<" ">") \(aq\(aq => (format\-pair "A" :open\-text "<" :close\-text ">") \(aq\(aq .ft P .fi .UNINDENT .UNINDENT .TP .B &rest The following parameter will contain a list of 0 or more positional arguments. No other positional parameters 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] (setv odd\-numbers (lfor x numbers :if (odd? x) x) even\-numbers (lfor x numbers :if (even? x) 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 .TP .B &kwonly New in version 0.12.0. .sp All following parmaeters can only be supplied as keywords. Like \fB&optional\fP, the parameter may be marked as optional by declaring it as a two\-element list containing the parameter name following by the default value. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (defn compare [a b &kwonly keyfn [reverse False]] \&... (setv result (keyfn a b)) \&... (if (not reverse) \&... result \&... (\- result))) => (compare "lisp" "python" \&... :keyfn (fn [x y] \&... (reduce \- (map (fn [s] (ord (first s))) [x y])))) \-4 => (compare "lisp" "python" \&... :keyfn (fn [x y] \&... (reduce \- (map (fn [s] (ord (first s))) [x y]))) \&... :reverse True) 4 .ft P .fi .UNINDENT .UNINDENT .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C => (compare "lisp" "python") Traceback (most recent call last): File "", line 1, in TypeError: compare() missing 1 required keyword\-only argument: \(aqkeyfn\(aq .ft P .fi .UNINDENT .UNINDENT .TP .B &kwargs Like \fB&rest\fP, but for keyword arugments. The following 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))) => (print\-parameters :parameter\-1 1 :parameter\-2 2) parameter_1 1 parameter_2 2 ; to avoid the mangling of \(aq\-\(aq to \(aq_\(aq, use unpacking: => (print\-parameters #** {"parameter\-1" 1 "parameter\-2" 2}) parameter\-1 1 parameter\-2 2 .ft P .fi .UNINDENT .UNINDENT .UNINDENT .sp The following example uses all of \fB&optional\fP, \fB&rest\fP, \fB&kwonly\fP, and \fB&kwargs\fP in order to show their interactions with each other. The function renders an HTML tag. It requires an argument \fBtag\-name\fP, a string which is the tag name. It has one optional argument, \fBdelim\fP, which defaults to \fB""\fP and is placed between each child. The rest of the arguments, \fBchildren\fP, are the tag\(aqs children or content. A single keyword\-only argument, \fBempty\fP, is included and defaults to \fBFalse\fP\&. \fBempty\fP changes how the tag is rendered if it has no children. Normally, a tag with no children is rendered like \fB
\fP\&. If \fBempty\fP is \fBTrue\fP, then it will render like \fB
\fP\&. The rest of the keyword arguments, \fBprops\fP, render as HTML attributes. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn render\-html\-tag [tag\-name &optional [delim ""] &rest children &kwonly [empty False] &kwargs attrs] \&... (setv rendered\-attrs (.join " " (lfor (, key val) (.items attrs) (+ (unmangle (str key)) "=\e"" (str val) "\e"")))) \&... (if rendered\-attrs ; If we have attributes, prefix them with a space after the tag name \&... (setv rendered\-attrs (+ " " rendered\-attrs))) \&... (setv rendered\-children (.join delim children)) \&... (if (and (not children) empty) \&... (+ "<" tag\-name rendered\-attrs " />") \&... (+ "<" tag\-name rendered\-attrs ">" rendered\-children ""))) => (render\-html\-tag "div") \(aq
=> (render\-html\-tag "img" :empty True) \(aq\(aq => (render\-html\-tag "img" :id "china" :class "big\-image" :empty True) \(aq\(aq => (render\-html\-tag "p" " \-\-\- " (render\-html\-tag "span" "" :class "fancy" "I\(aqm fancy!") "I\(aqm to the right of fancy" "I\(aqm alone :(") \(aq

I\e\(aqm fancy! \-\-\- I\e\(aqm to right right of fancy \-\-\- I\e\(aqm alone :(

\(aq .ft P .fi .UNINDENT .UNINDENT .SS defn/a .sp \fBdefn/a\fP macro is a variant of \fBdefn\fP that instead defines coroutines. It takes 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/a name [params] body) .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.argv) 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!) 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. .sp If you want fancy command\-line arguments, you can use the standard Python module \fBargparse\fP in the usual way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import argparse) (defmain [&rest _] (setv parser (argparse.ArgumentParser)) (.add\-argument parser "STRING" :help "string to replicate") (.add\-argument parser "\-n" :type int :default 3 :help "number of copies") (setv args (parser.parse_args)) (print (* args.STRING args.n)) 0) .ft P .fi .UNINDENT .UNINDENT .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/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 defmacro! .sp \fBdefmacro!\fP is like \fBdefmacro/g!\fP plus automatic once\-only evaluation for \fBo!\fP parameters, which are available as the equivalent \fBg!\fP symbol. .sp For example, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn expensive\-get\-number [] (print "spam") 14) => (defmacro triple\-1 [n] \(ga(+ ~n ~n ~n)) => (triple\-1 (expensive\-get\-number)) ; evals n three times spam spam spam 42 => (defmacro/g! triple\-2 [n] \(ga(do (setv ~g!n ~n) (+ ~g!n ~g!n ~g!n))) => (triple\-2 (expensive\-get\-number)) ; avoid repeats with a gensym spam 42 => (defmacro! triple\-3 [o!n] \(ga(+ ~g!n ~g!n ~g!n)) => (triple\-3 (expensive\-get\-number)) ; easier with defmacro! spam 42 .ft P .fi .UNINDENT .UNINDENT .SS deftag .sp New in version 0.13.0. .sp \fBdeftag\fP defines a tag macro. A tag macro is a unary macro that has the same semantics as an ordinary macro defined with \fBdefmacro\fP\&. It is called with the syntax \fB#tag FORM\fP, where \fBtag\fP is the name of the macro, and \fBFORM\fP is any form. The \fBtag\fP is often only one character, but it can be any symbol. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (deftag ♣ [expr] \(ga[~expr ~expr]) at 0x7f76d0271158> => #♣ 5 [5, 5] => (setv x 0) => #♣(+= x 1) [None, None] => x 2 .ft P .fi .UNINDENT .UNINDENT .sp In this example, if you used \fB(defmacro ♣ ...)\fP instead of \fB(deftag ♣ ...)\fP, you would call the macro as \fB(♣ 5)\fP or \fB(♣ (+= x 1))\fP\&. .sp The syntax for calling tag macros is similar to that of reader macros a la Common Lisp\(aqs \fBSET\-MACRO\-CHARACTER\fP\&. In fact, before Hy 0.13.0, tag macros were called "reader macros", and defined with \fBdefreader\fP rather than \fBdeftag\fP\&. True reader macros are not (yet) implemented in Hy. .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 (cut 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\-and\-compile .sp \fBeval\-and\-compile\fP is a special form that takes any number of forms. The input forms are evaluated as soon as the \fBeval\-and\-compile\fP form is compiled, instead of being deferred until run\-time. The input forms are also left in the program so they can be executed at run\-time as usual. So, if you compile and immediately execute a program (as calling \fBhy foo.hy\fP does when \fBfoo.hy\fP doesn\(aqt have an up\-to\-date byte\-compiled version), \fBeval\-and\-compile\fP forms will be evaluated twice. .sp One possible use of \fBeval\-and\-compile\fP is to make a function available both at compile\-time (so a macro can call it while expanding) and run\-time (so it can be called like any other function): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (eval\-and\-compile (defn add [x y] (+ x y))) (defmacro m [x] (add x 2)) (print (m 3)) ; prints 5 (print (add 3 6)) ; prints 9 .ft P .fi .UNINDENT .UNINDENT .sp Had the \fBdefn\fP not been wrapped in \fBeval\-and\-compile\fP, \fBm\fP wouldn\(aqt be able to call \fBadd\fP, because when the compiler was expanding \fB(m 3)\fP, \fBadd\fP wouldn\(aqt exist yet. .SS eval\-when\-compile .sp \fBeval\-when\-compile\fP is like \fBeval\-and\-compile\fP, but the code isn\(aqt executed at run\-time. Hence, \fBeval\-when\-compile\fP doesn\(aqt directly contribute any code to the final program, although it can still change Hy\(aqs state while compiling (e.g., by defining a function). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (eval\-when\-compile (defn add [x y] (+ x y))) (defmacro m [x] (add x 2)) (print (m 3)) ; prints 5 (print (add 3 6)) ; raises NameError: name \(aqadd\(aq is not defined .ft P .fi .UNINDENT .UNINDENT .SS first .sp \fBfirst\fP is a function 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 .sp It is implemented as \fB(next (iter coll) None)\fP, so it works with any iterable, and if given an empty iterable, it will return \fBNone\fP instead of raising an exception. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (first (repeat 10)) 10 => (first []) None .ft P .fi .UNINDENT .UNINDENT .SS for .sp \fBfor\fP is used to evaluate some forms for each element in an iterable object, such as a list. The return values of the forms are discarded and the \fBfor\fP form returns \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (for [x [1 2 3]] \&... (print "iterating") \&... (print x)) iterating 1 iterating 2 iterating 3 .ft P .fi .UNINDENT .UNINDENT .sp In its square\-bracketed first argument, \fBfor\fP allows the same types of clauses as \fI\%lfor\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (for [x [1 2 3] :if (!= x 2) y [7 8]] \&... (print x y)) 1 7 1 8 3 7 3 8 .ft P .fi .UNINDENT .UNINDENT .sp Furthermore, the last argument of \fBfor\fP can be an \fB(else …)\fP form. This form is executed after the last iteration of the \fBfor\fP\(aqs outermost iteration clause, but only if that outermost loop terminates normally. If it\(aqs jumped out of with e.g. \fBbreak\fP, the \fBelse\fP is ignored. .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 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) HySymbol(\(aq_G\euffff1\(aq) => (gensym "x") HySymbol(\(aq_x\euffff2\(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 collections. \fBget\fP takes at least 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 collection. If multiple \fIindex\fP or \fIkey\fP values are provided, they are used to access successive elements in a nested structure. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (do \&... (setv animals {"dog" "bark" "cat" "meow"} \&... numbers (, "zero" "one" "two" "three") \&... nested [0 1 ["a" "b" "c"] 3 4]) \&... (print (get animals "dog")) \&... (print (get numbers 2)) \&... (print (get nested 2 1))) bark two b .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 gfor .sp \fBgfor\fP creates a \fI\%generator expression\fP\&. Its syntax is the same as that of \fI\%lfor\fP\&. The difference is that \fBgfor\fP returns an iterator, which evaluates and yields values one at a time. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv accum []) => (list (take\-while \&... (fn [x] (< x 5)) \&... (gfor x (count) :do (.append accum x) x))) [0, 1, 2, 3, 4] => accum [0, 1, 2, 3, 4, 5] .ft P .fi .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 raised 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* / if\-not .sp New in version 0.10.0: if\-not .sp \fBif / if* / if\-not\fP respect Python \fItruthiness\fP, that is, a \fItest\fP fails if it evaluates to a "zero" (including values of \fBlen\fP zero, \fBNone\fP, and \fBFalse\fP), and passes otherwise, but values with a \fB__bool__\fP method can override this. .sp The \fBif\fP macro is for conditionally selecting an expression for evaluation. The result of the selected expression becomes the result of the entire \fBif\fP form. \fBif\fP can select a group of expressions with the help of a \fBdo\fP block. .sp \fBif\fP takes any number of alternating \fItest\fP and \fIthen\fP expressions, plus an optional \fIelse\fP expression at the end, which defaults to \fBNone\fP\&. \fBif\fP checks each \fItest\fP in turn, and selects the \fIthen\fP corresponding to the first passed test. \fBif\fP does not evaluate any expressions following its selection, similar to the \fBif/elif/else\fP control structure from Python. If no tests pass, \fBif\fP selects \fIelse\fP\&. .sp The \fBif*\fP special form is restricted to 2 or 3 arguments, but otherwise works exactly like \fBif\fP (which expands to nested \fBif*\fP forms), so there is generally no reason to use it directly. .sp \fBif\-not\fP is similar to \fBif*\fP but the second expression will be executed when the condition fails while the third and final expression is executed when the test succeeds \-\- the opposite order of \fBif*\fP\&. The final expression is again optional and defaults to \fBNone\fP\&. .sp Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (if (< n 0.0) "negative" (= n 0.0) "zero" (> n 0.0) "positive" "not a number")) (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 .SS lif and lif\-not .sp New in version 0.10.0. .sp New in version 0.11.0: lif\-not .sp For those that prefer a more Lispy \fBif\fP clause, we have \fBlif\fP\&. This \fIonly\fP considers \fBNone\fP to be false! All other "false\-ish" Python values are considered true. Conversely, we have \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 => (lif True "true" "false") "true" => (lif False "true" "false") "true" => (lif 0 "true" "false") "true" => (lif None "true" "false") "false" => (lif\-not None "true" "false") "true" => (lif\-not False "true" "false") "false" .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. ;; ;; Python: ;; from tests.resources import kwtest, function_with_a_dash ;; from os.path import exists, isdir as is_dir, isfile as is_file ;; import sys as systest (import [tests.resources [kwtest function\-with\-a\-dash]] [os.path [exists isdir :as dir? isfile :as file?]] [sys :as systest]) ;; Import all module functions into current namespace ;; ;; Python: from sys import * (import [sys [*]]) .ft P .fi .UNINDENT .UNINDENT .SS fn .sp \fBfn\fP, like Python\(aqs \fBlambda\fP, can be used to define an anonymous function. Unlike Python\(aqs \fBlambda\fP, the body of the function can comprise several statements. The parameters are similar to \fBdefn\fP: the first parameter is vector of parameters and the rest is the body of the function. \fBfn\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 => (setv 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 fn/a .sp \fBfn/a\fP is a variant of \fBfn\fP than defines an anonymous coroutine. The parameters are similar to \fBdefn/a\fP: the first parameter is vector of parameters and the rest is the body of the function. \fBfn/a\fP returns a new coroutine. .SS last .sp New in version 0.11.0. .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 lfor .sp The comprehension forms \fBlfor\fP, \fI\%sfor\fP, \fI\%dfor\fP, \fI\%gfor\fP, and \fI\%for\fP are used to produce various kinds of loops, including Python\-style \fI\%comprehensions\fP\&. \fBlfor\fP in particular creates a list comprehension. A simple use of \fBlfor\fP is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (lfor x (range 5) (* 2 x)) [0, 2, 4, 6, 8] .ft P .fi .UNINDENT .UNINDENT .sp \fBx\fP is the name of a new variable, which is bound to each element of \fB(range 5)\fP\&. Each such element in turn is used to evaluate the value form \fB(* 2 x)\fP, and the results are accumulated into a list. .sp Here\(aqs a more complex example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (lfor \&... x (range 3) \&... y (range 3) \&... :if (!= x y) \&... :setv total (+ x y) \&... [x y total]) [[0, 1, 1], [0, 2, 2], [1, 0, 1], [1, 2, 3], [2, 0, 2], [2, 1, 3]] .ft P .fi .UNINDENT .UNINDENT .sp When there are several iteration clauses (here, the pairs of forms \fBx (range 3)\fP and \fBy (range 3)\fP), the result works like a nested loop or Cartesian product: all combinations are considered in lexicographic order. .sp The general form of \fBlfor\fP is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (lfor CLAUSES VALUE) .ft P .fi .UNINDENT .UNINDENT .sp where the \fBVALUE\fP is an arbitrary form that is evaluated to produce each element of the result list, and \fBCLAUSES\fP is any number of clauses. There are several types of clauses: .INDENT 0.0 .IP \(bu 2 Iteration clauses, which look like \fBLVALUE ITERABLE\fP\&. The \fBLVALUE\fP is usually just a symbol, but could be something more complicated, like \fB[x y]\fP\&. .IP \(bu 2 \fB:async LVALUE ITERABLE\fP, which is an \fI\%asynchronous\fP form of iteration clause. .IP \(bu 2 \fB:do FORM\fP, which simply evaluates the \fBFORM\fP\&. If you use \fB(continue)\fP or \fB(break)\fP here, they will apply to the innermost iteration clause before the \fB:do\fP\&. .IP \(bu 2 \fB:setv LVALUE RVALUE\fP, which is equivalent to \fB:do (setv LVALUE RVALUE)\fP\&. .IP \(bu 2 \fB:if CONDITION\fP, which is equivalent to \fB:do (unless CONDITION (continue))\fP\&. .UNINDENT .sp For \fBlfor\fP, \fBsfor\fP, \fBgfor\fP, and \fBdfor\fP, variables are scoped as if the comprehension form were its own function, so variables defined by an iteration clause or \fB:setv\fP are not visible outside the form. In fact, these forms are implemented as generator functions whenever they contain Python statements, with the attendant consequences for calling \fBreturn\fP\&. By contrast, \fBfor\fP shares the caller\(aqs scope. .SS nonlocal .sp New in version 0.11.1. .sp \fBnonlocal\fP can be used to mark a symbol as not local to the current scope. The parameters are the names of symbols to mark as nonlocal. This is necessary to modify variables through nested \fBfn\fP scopes: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defn some\-function [] (setv x 0) (register\-some\-callback (fn [stuff] (nonlocal x) (setv x stuff)))) .ft P .fi .UNINDENT .UNINDENT .sp Without the call to \fB(nonlocal x)\fP, the inner function would redefine \fBx\fP to \fBstuff\fP inside its local scope instead of overwriting the \fBx\fP in the outer function. .sp See \fI\%PEP3104\fP for further information. .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 => (or False False) False => (or 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 of .sp \fBof\fP is an alias for get, but with special semantics designed for handling PEP 484\(aqs generic types. .sp \fBof\fP has three forms: .INDENT 0.0 .IP \(bu 2 \fB(of T)\fP will simply become \fBT\fP\&. .IP \(bu 2 \fB(of T x)\fP will become \fB(get T x)\fP\&. .IP \(bu 2 \fB(of T x y ...)\fP (where the \fB\&...\fP represents zero or more arguments) will become \fB(get T (, x y ...))\fP\&. .UNINDENT .sp For instance: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (of str) ; => str (of List int) ; => List[int] (of Set int) ; => Set[int] (of Dict str str) ; => Dict[str, str] (of Tuple str int) ; => Tuple[str, int] (of Callable [int str] str) ; => Callable[[int, str], str] .ft P .fi .UNINDENT .UNINDENT .SS py .sp \fBpy\fP parses the given Python code at compile\-time and inserts the result into the generated abstract syntax tree. Thus, you can mix Python code into a Hy program. Only a Python expression is allowed, not statements; use \fI\%pys\fP if you want to use Python statements. The value of the expression is returned from the \fBpy\fP form. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print "A result from Python:" (py "\(aqhello\(aq + \(aqworld\(aq")) .ft P .fi .UNINDENT .UNINDENT .sp The code must be given as a single string literal, but you can still use macros, eval\-fn, and related tools to construct the \fBpy\fP form. If having to backslash\-escape internal double quotes is getting you down, try a bracket string\&. If you want to evaluate some Python code that\(aqs only defined at run\-time, try the standard Python function \fI\%eval()\fP\&. .sp Python code need not syntactically round\-trip if you use \fBhy2py\fP on a Hy program that uses \fBpy\fP or \fBpys\fP\&. For example, comments will be removed. .SS pys .sp As \fI\%py\fP, but the code can consist of zero or more statements, including compound statements such as \fBfor\fP and \fBdef\fP\&. \fBpys\fP always returns \fBNone\fP\&. Also, the code string is dedented with \fI\%textwrap.dedent()\fP before parsing, which allows you to intend the code to match the surrounding Hy code, but significant leading whitespace in embedded string literals will be removed. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (pys "myvar = 5") (print "myvar is" myvar) .ft P .fi .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")) => x ; variable x is set to unevaluated expression HyExpression([ HySymbol(\(aqprint\(aq), HyString(\(aqHello World\(aq)]) => (eval x) Hello World .ft P .fi .UNINDENT .UNINDENT .SS require .sp \fBrequire\fP is used to import macros from one or more given modules. It allows parameters in all the same formats as \fBimport\fP\&. The \fBrequire\fP form itself produces no code in the final program: its effect is purely at compile\-time, for the benefit of macro expansion. Specifically, \fBrequire\fP imports each named module and then makes each requested macro available in the current module. .sp The following are all equivalent ways to call a macro named \fBfoo\fP in the module \fBmymodule\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require mymodule) (mymodule.foo 1) (require [mymodule :as M]) (M.foo 1) (require [mymodule [foo]]) (foo 1) (require [mymodule [*]]) (foo 1) (require [mymodule [foo :as bar]]) (bar 1) .ft P .fi .UNINDENT .UNINDENT .SS Macros that call macros .sp One aspect of \fBrequire\fP that may be surprising is what happens when one macro\(aqs expansion calls another macro. Suppose \fBmymodule.hy\fP looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro repexpr [n expr] ; Evaluate the expression n times ; and collect the results in a list. \(ga(list (map (fn [_] ~expr) (range ~n)))) (defmacro foo [n] \(ga(repexpr ~n (input "Gimme some input: "))) .ft P .fi .UNINDENT .UNINDENT .sp And then, in your main program, you write: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require [mymodule [foo]]) (print (mymodule.foo 3)) .ft P .fi .UNINDENT .UNINDENT .sp Running this raises \fBNameError: name \(aqrepexpr\(aq is not defined\fP, even though writing \fB(print (foo 3))\fP in \fBmymodule\fP works fine. The trouble is that your main program doesn\(aqt have the macro \fBrepexpr\fP available, since it wasn\(aqt imported (and imported under exactly that name, as opposed to a qualified name). You could do \fB(require [mymodule [*]])\fP or \fB(require [mymodule [foo repexpr]])\fP, but a less error\-prone approach is to change the definition of \fBfoo\fP to require whatever sub\-macros it needs: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro foo [n] \(ga(do (require mymodule) (mymodule.repexpr ~n (input "Gimme some input: ")))) .ft P .fi .UNINDENT .UNINDENT .sp It\(aqs wise to use \fB(require mymodule)\fP here rather than \fB(require [mymodule [repexpr]])\fP to avoid accidentally shadowing a function named \fBrepexpr\fP in the main program. .SS Qualified macro names .sp Note that in the current implementation, there\(aqs a trick in qualified macro names, like \fBmymodule.foo\fP and \fBM.foo\fP in the above example. These names aren\(aqt actually attributes of module objects; they\(aqre just identifiers with periods in them. In fact, \fBmymodule\fP and \fBM\fP aren\(aqt defined by these \fBrequire\fP forms, even at compile\-time. None of this will hurt you unless try to do introspection of the current module\(aqs set of defined macros, which isn\(aqt really supported anyway. .SS rest .sp \fBrest\fP takes the given collection and returns an iterable of all but the first element. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (rest (range 10))) [1, 2, 3, 4, 5, 6, 7, 8, 9] .ft P .fi .UNINDENT .UNINDENT .sp Given an empty collection, it returns an empty iterable. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (rest [])) [] .ft P .fi .UNINDENT .UNINDENT .SS return .sp \fBreturn\fP compiles to a \fI\%return\fP statement. It exits the current function, returning its argument if provided with one or \fBNone\fP if not. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn f [x] (for [n (range 10)] (when (> n x) (return n)))) => (f 3.9) 4 .ft P .fi .UNINDENT .UNINDENT .sp Note that in Hy, \fBreturn\fP is necessary much less often than in Python, since the last form of a function is returned automatically. Hence, an explicit \fBreturn\fP is only necessary to exit a function early. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn f [x] (setv y 10) (+ x y)) => (f 4) 14 .ft P .fi .UNINDENT .UNINDENT .sp To get Python\(aqs behavior of returning \fBNone\fP when execution reaches the end of a function, put \fBNone\fP there yourself. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn f [x] (setv y 10) (+ x y) None) => (print (f 4)) None .ft P .fi .UNINDENT .UNINDENT .SS sfor .sp \fBsfor\fP creates a set comprehension. \fB(sfor CLAUSES VALUE)\fP is equivalent to \fB(set (lfor CLAUSES VALUE))\fP\&. See \fI\%lfor\fP\&. .SS cut .sp \fBcut\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 cut. 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 \fBcut\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 => (setv collection (range 10)) => (cut collection) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] => (cut collection 5) [5, 6, 7, 8, 9] => (cut collection 2 8) [2, 3, 4, 5, 6, 7] => (cut collection 2 8 2) [2, 4, 6] => (cut collection \-4 \-2) [6, 7] .ft P .fi .UNINDENT .UNINDENT .SS raise .sp The \fBraise\fP form can be used to raise an \fBException\fP at runtime. Example usage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (raise) ; re\-rase the last exception (raise IOError) ; raise an IOError (raise (IOError "foobar")) ; raise an IOError("foobar") .ft P .fi .UNINDENT .UNINDENT .sp \fBraise\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 catch exceptions (\fBexcept\fP) and run cleanup actions (\fBfinally\fP). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (try (error\-prone\-function) (another\-error\-prone\-function) (except [ZeroDivisionError] (print "Division by zero")) (except [[IndexError KeyboardInterrupt]] (print "Index error or Ctrl\-C")) (except [e ValueError] (print "ValueError:" (repr e))) (except [e [TabError PermissionError ReferenceError]] (print "Some sort of error:" (repr e))) (else (print "No errors")) (finally (print "All done"))) .ft P .fi .UNINDENT .UNINDENT .sp The first argument of \fBtry\fP is its body, which can contain one or more forms. Then comes any number of \fBexcept\fP clauses, then optionally an \fBelse\fP clause, then optionally a \fBfinally\fP clause. If an exception is raised with a matching \fBexcept\fP clause during the execution of the body, that \fBexcept\fP clause will be executed. If no exceptions are raised, the \fBelse\fP clause is executed. The \fBfinally\fP clause will be executed last regardless of whether an exception was raised. .sp The return value of \fBtry\fP is the last form of the \fBexcept\fP clause that was run, or the last form of \fBelse\fP if no exception was raised, or the \fBtry\fP body if there is no \fBelse\fP clause. .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 unpack\-iterable, unpack\-mapping .sp (Also known as the splat operator, star operator, argument expansion, argument explosion, argument gathering, and varargs, among others...) .sp \fBunpack\-iterable\fP and \fBunpack\-mapping\fP allow an iterable or mapping object (respectively) to provide positional or keywords arguments (respectively) to a function. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defn f [a b c d] [a b c d]) => (f (unpack\-iterable [1 2]) (unpack\-mapping {"c" 3 "d" 4})) [1, 2, 3, 4] .ft P .fi .UNINDENT .UNINDENT .sp \fBunpack\-iterable\fP is usually written with the shorthand \fB#*\fP, and \fBunpack\-mapping\fP with \fB#**\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (f #* [1 2] #** {"c" 3 "d" 4}) [1, 2, 3, 4] .ft P .fi .UNINDENT .UNINDENT .sp Unpacking is allowed in a variety of contexts, and you can unpack more than once in one expression (\fI\%PEP 3132\fP, \fI\%PEP 448\fP). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv [a #* b c] [1 2 3 4 5]) => [a b c] [1, [2, 3, 4], 5] => [#* [1 2] #* [3 4]] [1, 2, 3, 4] => {#** {1 2} #** {3 4}} {1: 2, 3: 4} => (f #* [1] #* [2] #** {"c" 3} #** {"d" 4}) [1, 2, 3, 4] .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 => (setv nickname "Cuddles") => (quasiquote (= nickname (unquote nickname))) HyExpression([ HySymbol(\(aq=\(aq), HySymbol(\(aqnickname\(aq), \(aqCuddles\(aq]) => \(ga(= nickname ~nickname) HyExpression([ HySymbol(\(aq=\(aq), HySymbol(\(aqnickname\(aq), \(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 be used when the symbol being unquoted contains an iterable value, as it "splices" that iterable into the quasiquoted form. \fBunquote\-splice\fP can also be used when the value evaluates to a false value such as \fBNone\fP, \fBFalse\fP, or \fB0\fP, in which case the value is treated as an empty list and thus does not splice anything into the form. \fBunquote\-splice\fP is aliased to the \fB~@\fP syntax. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv nums [1 2 3 4]) => (quasiquote (+ (unquote\-splice nums))) HyExpression([ HySymbol(\(aq+\(aq), 1, 2, 3, 4]) => \(ga(+ ~@nums) HyExpression([ HySymbol(\(aq+\(aq), 1, 2, 3, 4]) => \(ga[1 2 ~@(if (neg? (first nums)) nums)] HyList([ HyInteger(1), HyInteger(2)]) .ft P .fi .UNINDENT .UNINDENT .sp Here, the last example evaluates to \fB(\(aq+\(aq 1 2)\fP, since the condition \fB(< (nth nums 0) 0)\fP is \fBFalse\fP, which makes this \fBif\fP expression evaluate to \fBNone\fP, because the \fBif\fP expression here does not have an else clause. \fBunquote\-splice\fP then evaluates this as an empty value, leaving no effects on the list it is enclosed in, therefore resulting in \fB(\(aq+\(aq 1 2)\fP\&. .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 compiles to a \fI\%while\fP statement. It is used to execute a set of forms as long as a condition is met. The first argument to \fBwhile\fP is the condition, and any remaining forms constitute the body. 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 .sp The last form of a \fBwhile\fP loop can be an \fBelse\fP clause, which is executed after the loop terminates, unless it exited abnormally (e.g., with \fBbreak\fP). So, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv x 2) (while x (print "In body") (\-= x 1) (else (print "In else"))) .ft P .fi .UNINDENT .UNINDENT .sp prints .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C In body In body In else .ft P .fi .UNINDENT .UNINDENT .sp If you put a \fBbreak\fP or \fBcontinue\fP form in the condition of a \fBwhile\fP loop, it will apply to the very same loop rather than an outer loop, even if execution is yet to ever reach the loop body. (Hy compiles a \fBwhile\fP loop with statements in its condition by rewriting it so that the condition is actually in the body.) So, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (for [x [1]] (print "In outer loop") (while (do (print "In condition") (break) (print "This won\(aqt print.") True) (print "This won\(aqt print, either.")) (print "At end of outer loop")) .ft P .fi .UNINDENT .UNINDENT .sp prints .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C In outer loop In condition At end of outer loop .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 .sp \fBwith\fP returns the value of its last form, unless it suppresses an exception (because the context manager\(aqs \fB__exit__\fP method returned true), in which case it returns \fBNone\fP\&. So, the previous example could also be written .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (print (with [f (open "NEWS")] (.read f))) .ft P .fi .UNINDENT .UNINDENT .SS with/a .sp \fBwith/a\fP behaves like \fBwith\fP, but is used to wrap the execution of a block within an asynchronous context manager. The context manager can then set up the local system and tear it down in a controlled manner asynchronously. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (with/a [arg (expr)] block) (with/a [(expr)] block) (with/a [arg (expr) (expr)] block) .ft P .fi .UNINDENT .UNINDENT .sp \fBwith/a\fP returns the value of its last form, unless it suppresses an exception (because the context manager\(aqs \fB__aexit__\fP method returned true), in which case it returns \fBNone\fP\&. .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 #@ .sp New in version 0.12.0. .sp The tag macro \fB#@\fP can be used as a shorthand for \fBwith\-decorator\fP\&. With \fB#@\fP, the previous example becomes: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => #@(inc\-decorator (defn addition [a b] (+ a b))) => (addition 1 1) 4 => #@(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 (do (setv 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 xor .sp New in version 0.12.0. .sp \fBxor\fP performs the logical operation of exclusive OR. It takes two arguments. If exactly one argument is true, that argument is returned. If neither is true, the second argument is returned (which will necessarily be false). Otherwise, when both arguments are true, the value \fBFalse\fP is returned. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => [(xor 0 0) (xor 0 1) (xor 1 0) (xor 1 1)] [0, 1, 1, False] .ft P .fi .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 (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 (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 \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 [])) [] => (list (take 5 (butlast (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 comp .sp Usage: \fB(comp f g)\fP .sp Compose zero or more functions into a new function. The new function will chain the given functions together, so \fB((comp g f) x)\fP is equivalent to \fB(g (f x))\fP\&. Called without arguments, \fBcomp\fP returns \fBidentity\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv example (comp str +)) => (example 1 2 3) "6" => (setv simple (comp)) => (simple "hello") "hello" .ft P .fi .UNINDENT .UNINDENT .SS complement .sp New in version 0.12.0. .sp Usage: \fB(complement f)\fP .sp Returns a new function that returns the same thing as \fBf\fP, but logically inverted. So, \fB((complement f) x)\fP is equivalent to \fB(not (f x))\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv inverse (complement identity)) => (inverse True) False => (inverse 1) False => (inverse False) True .ft P .fi .UNINDENT .UNINDENT .SS constantly .sp New in version 0.12.0. .sp Usage \fB(constantly 42)\fP .sp Create a new function that always returns the given value, regardless of the arguments given to it. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv answer (constantly 42)) => (answer) 42 => (answer 1 2 3) 42 => (answer 1 :foo 2) 42 .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 eval .sp \fBeval\fP evaluates a quoted expression and returns the value. The optional second and third arguments specify the dictionary of globals to use and the module name. The globals dictionary defaults to \fB(local)\fP and the module name defaults to the name of the current module. An optional fourth keyword parameter, \fBcompiler\fP, allows one to re\-use an existing \fBHyASTCompiler\fP object for the compilation step. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (eval \(aq(print "Hello World")) "Hello World" .ft P .fi .UNINDENT .UNINDENT .sp If you want to evaluate a string, use \fBread\-str\fP to convert it to a form first: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (eval (read\-str "(+ 1 1)")) 2 .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 fraction .sp Returns a Python object of type \fBfractions.Fraction\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (fraction 1 2) Fraction(1, 2) .ft P .fi .UNINDENT .UNINDENT .sp Note that Hy has a built\-in fraction literal that does the same thing: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => 1/2 Fraction(1, 2) .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 (\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 juxt .sp New in version 0.12.0. .sp Usage: \fB(juxt f &rest fs)\fP .sp Return a function that applies each of the supplied functions to a single set of arguments and collects the results into a list. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => ((juxt min max sum) (range 1 101)) [1, 100, 5050] => (dict (map (juxt identity ord) "abcdef")) {\(aqf\(aq: 102, \(aqd\(aq: 100, \(aqb\(aq: 98, \(aqe\(aq: 101, \(aqc\(aq: 99, \(aqa\(aq: 97} => ((juxt + \- * /) 24 3) [27, 21, 72, 8.0] .ft P .fi .UNINDENT .UNINDENT .SS keyword .sp New in version 0.10.1. .sp Usage: \fB(keyword "foo")\fP .sp Create a keyword from the given value. Strings, numbers, and even objects with the \fI__name__\fP magic will work. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (keyword "foo") HyKeyword(\(aqfoo\(aq) => (keyword 1) HyKeyword(\(aqfoo\(aq) .ft P .fi .UNINDENT .UNINDENT .SS keyword? .sp New in version 0.10.1. .sp Usage: \fB(keyword? foo)\fP .sp Check whether \fIfoo\fP is a keyword\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (keyword? :foo) True => (setv foo 1) => (keyword? foo) False .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))) HyExpression([ HySymbol(\(aqx\(aq), HyExpression([ HySymbol(\(aqa\(aq), HySymbol(\(aqb\(aq)]), HySymbol(\(aqy\(aq)]) => (macroexpand \(aq(\-> (a b) (\-> (c d) (e f)))) HyExpression([ HySymbol(\(aqe\(aq), HyExpression([ HySymbol(\(aqc\(aq), HyExpression([ HySymbol(\(aqa\(aq), HySymbol(\(aqb\(aq)]), HySymbol(\(aqd\(aq)]), HySymbol(\(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)))) HyExpression([ HySymbol(\(aq_>\(aq), HyExpression([ HySymbol(\(aqa\(aq), HySymbol(\(aqb\(aq)]), HyExpression([ HySymbol(\(aqc\(aq), HySymbol(\(aqd\(aq)]), HyExpression([ HySymbol(\(aqe\(aq), HySymbol(\(aqf\(aq)])]) .ft P .fi .UNINDENT .UNINDENT .SS mangle .sp Usage: \fB(mangle x)\fP .sp Stringify the input and translate it according to Hy\(aqs mangling rules\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (mangle "foo\-bar") \(aqfoo_bar\(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 + {"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 name .sp New in version 0.10.1. .sp Usage: \fB(name :keyword)\fP .sp Convert the given value to a string. Keyword special character will be stripped. Strings will be used as is. Even objects with the \fI__name__\fP magic will work. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (name :foo) u\(aqfoo\(aq .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 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 => (setv 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 None])\fP .sp Returns the \fIn\fP\-th item in a collection, counting from 0. Return the default value, \fBNone\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 => (none? (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 parse\-args .sp Usage: \fB(parse\-args spec &optional args &kwargs parser\-args)\fP .sp Return arguments namespace parsed from \fIargs\fP or \fBsys.argv\fP with \fI\%argparse.ArgumentParser.parse_args()\fP according to \fIspec\fP\&. .sp \fIspec\fP should be a list of arguments which will be passed to repeated calls to \fI\%argparse.ArgumentParser.add_argument()\fP\&. \fIparser\-args\fP may be a list of keyword arguments to pass to the \fI\%argparse.ArgumentParser\fP constructor. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (parse\-args [["strings" :nargs "+" :help "Strings"] ["\-n" "\-\-numbers" :action "append" :type int :help "Numbers"]] ["a" "b" "\-n" "1" "\-n" "2"] :description "Parse strings and numbers from args") Namespace(numbers=[1, 2], strings=[\(aqa\(aq, \(aqb\(aq]) .ft P .fi .UNINDENT .UNINDENT .SS partition .sp Usage: \fB(partition coll [n] [step] [fillvalue])\fP .sp Chunks \fIcoll\fP into \fIn\fP\-tuples (pairs by default). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (partition (range 10))) ; n=2 [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] .ft P .fi .UNINDENT .UNINDENT .sp The \fIstep\fP defaults to \fIn\fP, but can be more to skip elements, or less for a sliding window with overlap. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (partition (range 10) 2 3)) [(0, 1), (3, 4), (6, 7)] => (list (partition (range 5) 2 1)) [(0, 1), (1, 2), (2, 3), (3, 4)] .ft P .fi .UNINDENT .UNINDENT .sp The remainder, if any, is not included unless a \fIfillvalue\fP is specified. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list (partition (range 10) 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] => (list (partition (range 10) 3 :fillvalue "x")) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, \(aqx\(aq, \(aqx\(aq)] .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 \fBNone\fP\&. Return \fBNone\fP if \fIcoll\fP is empty. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (some even? [2 4 6]) True => (none? (some even? [1 3 5])) True => (none? (some identity [0 "" []])) True => (some identity [0 "non\-empty\-string" []]) \(aqnon\-empty\-string\(aq => (none? (some even? [])) True .ft P .fi .UNINDENT .UNINDENT .SS list? .sp Usage: \fB(list? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a list. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (list? \(aq(inc 41)) True => (list? \(aq42) False .ft P .fi .UNINDENT .UNINDENT .SS string? .sp Usage: \fB(string? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a string (\fBstr\fP). .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 tuple? .sp Usage: \fB(tuple? x)\fP .sp Returns \fBTrue\fP if \fIx\fP is a tuple. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (tuple? (, 42 44)) True => (tuple? [42 44]) 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))) [] => (list (take 5 (drop\-last 100 (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) HyExpression([ HySymbol(\(aq+\(aq), HyInteger(2), HyInteger(2)]) => (eval (read)) (+ 2 2) 4 => (import io) => (setv buffer (io.StringIO "(+ 2 2)\en(\- 2 1)")) => (eval (read :from\-file buffer)) 4 => (eval (read :from\-file buffer)) 1 => (with [f (open "example.hy" "w")] \&... (.write f "(print \(aqhello)\en(print \e"hyfriends!\e")")) 35 => (with [f (open "example.hy")] \&... (try (while True \&... (setv exp (read f)) \&... (print "OHY" exp) \&... (eval exp)) \&... (except [e EOFError] \&... (print "EOF!")))) OHY HyExpression([ HySymbol(\(aqprint\(aq), HyExpression([ HySymbol(\(aqquote\(aq), HySymbol(\(aqhello\(aq)])]) hello OHY HyExpression([ HySymbol(\(aqprint\(aq), HyString(\(aqhyfriends!\(aq)]) hyfriends! EOF! .ft P .fi .UNINDENT .UNINDENT .SS read\-str .sp Usage: \fB(read\-str "string")\fP .sp This is essentially a wrapper around \fIread\fP which reads expressions from a string: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (read\-str "(print 1)") HyExpression([ HySymbol(\(aqprint\(aq), HyInteger(1)]) => (eval (read\-str "(print 1)")) 1 .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 unmangle .sp Usage: \fB(unmangle x)\fP .sp Stringify the input and return a string that would mangle to it. Note that this isn\(aqt a one\-to\-one operation, and nor is \fBmangle\fP, so \fBmangle\fP and \fBunmangle\fP don\(aqt always round\-trip. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (unmangle "foo_bar") \(aqfoo\-bar\(aq .ft P .fi .UNINDENT .UNINDENT .SS Included itertools .SS count cycle repeat accumulate chain compress drop\-while remove group\-by islice .nf * .fi map take\-while tee zip\-longest product permutations combinations multicombinations .sp All of Python\(aqs \fI\%itertools\fP are available. Some of their names have been changed: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fBstarmap\fP has been changed to \fB*map\fP .IP \(bu 2 \fBcombinations_with_replacement\fP has been changed to \fBmulticombinations\fP .IP \(bu 2 \fBgroupby\fP has been changed to \fBgroup\-by\fP .IP \(bu 2 \fBtakewhile\fP has been changed to \fBtake\-while\fP .IP \(bu 2 \fBdropwhile\fP has been changed to \fBdrop\-while\fP .IP \(bu 2 \fBfilterfalse\fP has been changed to \fBremove\fP .UNINDENT .UNINDENT .UNINDENT .SS Model Patterns .sp The module \fBhy.model\-patterns\fP provides a library of parser combinators for parsing complex trees of Hy models. Model patterns exist mostly to help implement the compiler, but they can also be useful for writing macros. .SS A motivating example .sp The kind of problem that model patterns are suited for is the following. Suppose you want to validate and extract the components of a form like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (setv form \(aq(try (foo1) (foo2) (except [EType1] (foo3)) (except [e EType2] (foo4) (foo5)) (except [] (foo6)) (finally (foo7) (foo8)))) .ft P .fi .UNINDENT .UNINDENT .sp You could do this with loops and indexing, but it would take a lot of code and be error\-prone. Model patterns concisely express the general form of an expression to be matched, like what a regular expression does for text. Here\(aqs a pattern for a \fBtry\fP form of the above kind: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import [funcparserlib.parser [maybe many]]) (import [hy.model\-patterns [*]]) (setv parser (whole [ (sym "try") (many (notpexpr "except" "else" "finally")) (many (pexpr (sym "except") (| (brackets) (brackets FORM) (brackets SYM FORM)) (many FORM))) (maybe (dolike "else")) (maybe (dolike "finally"))])) .ft P .fi .UNINDENT .UNINDENT .sp You can run the parser with \fB(.parse parser form)\fP\&. The result is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (, [\(aq(foo1) \(aq(foo2)] [ \(aq([EType1] [(foo3)]) \(aq([e EType2] [(foo4) (foo5)]) \(aq([] [(foo6)])] None \(aq((foo7) (foo8))) .ft P .fi .UNINDENT .UNINDENT .sp which is conveniently utilized with an assignment such as \fB(setv [body except\-clauses else\-part finally\-part] result)\fP\&. Notice that \fBelse\-part\fP will be set to \fBNone\fP because there is no \fBelse\fP clause in the original form. .SS Usage .sp Model patterns are implemented as \fI\%funcparserlib\fP parser combinators. We won\(aqt reproduce funcparserlib\(aqs own documentation, but here are some important built\-in parsers: .INDENT 0.0 .IP \(bu 2 \fB(+ ...)\fP matches its arguments in sequence. .IP \(bu 2 \fB(| ...)\fP matches any one of its arguments. .IP \(bu 2 \fB(>> parser function)\fP matches \fBparser\fP, then feeds the result through \fBfunction\fP to change the value that\(aqs produced on a successful parse. .IP \(bu 2 \fB(skip parser)\fP matches \fBparser\fP, but doesn\(aqt add it to the produced value. .IP \(bu 2 \fB(maybe parser)\fP matches \fBparser\fP if possible. Otherwise, it produces the value \fBNone\fP\&. .IP \(bu 2 \fB(some function)\fP takes a predicate \fBfunction\fP and matches a form if it satisfies the predicate. .UNINDENT .sp The best reference for Hy\(aqs parsers is the docstrings (use \fB(help hy.model\-patterns)\fP), but again, here are some of the more important ones: .INDENT 0.0 .IP \(bu 2 \fBFORM\fP matches anything. .IP \(bu 2 \fBSYM\fP matches any symbol. .IP \(bu 2 \fB(sym "foo")\fP or \fB(sym ":foo")\fP matches and discards (per \fBskip\fP) the named symbol or keyword. .IP \(bu 2 \fB(brackets ...)\fP matches the arguments in square brackets. .IP \(bu 2 \fB(pexpr ...)\fP matches the arguments in parentheses. .UNINDENT .sp Here\(aqs how you could write a simple macro using model patterns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defmacro pairs [&rest args] (import [funcparserlib.parser [many]]) (import [hy.model\-patterns [whole SYM FORM]]) (setv [args] (\->> args (.parse (whole [ (many (+ SYM FORM))])))) \(ga[~@(\->> args (map (fn [x] (, (name (get x 0)) (get x 1)))))]) (print (pairs a 1 b 2 c 3)) ; => [["a" 1] ["b" 2] ["c" 3]] .ft P .fi .UNINDENT .UNINDENT .sp A failed parse will raise \fBfuncparserlib.parser.NoParseError\fP\&. .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. .sp Hy uses pretty\-printing reprs for its compound models by default. If this is causing issues, it can be turned off globally by setting \fBhy.models.PRETTY\fP to \fBFalse\fP, or temporarily by using the \fBhy.models.pretty\fP context manager. .sp Hy also attempts to color pretty reprs and errors using \fBcolorama\fP\&. These can be turned off globally by setting \fBhy.models.COLORED\fP and \fBhy.errors.COLORED\fP, respectively, to \fBFalse\fP\&. .SS HySequence .sp \fBhy.models.HySequence\fP is the abstract base class of "iterable" Hy models, such as HyExpression and HyList. .sp Adding a HySequence 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. .sp HySequences are (mostly) immutable: you can\(aqt add, modify, or remove elements. You can still append to a variable containing a HySequence with \fB+=\fP and otherwise construct new HySequences out of old ones. .SS HyList .sp \fBhy.models.HyList\fP is a \fI\%HySequence\fP for bracketed \fB[]\fP lists, which, when used as a top\-level expression, translate to Python list literals in the compilation phase. .SS HyExpression .sp \fBhy.models.HyExpression\fP inherits \fI\%HySequence\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.HyDict\fP inherits \fI\%HySequence\fP for curly\-bracketed \fB{}\fP expressions, which compile down to a Python dictionary literal. .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.HyString\fP represents string literals (including bracket strings), which compile down to unicode string literals (\fBstr\fP) in Python. .sp \fBHyString\fPs 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. .sp \fBHyString\fPs have an attribute \fBbrackets\fP that stores the custom delimiter used for a bracket string (e.g., \fB"=="\fP for \fB#[==[hello world]==]\fP and the empty string for \fB#[[hello world]]\fP). \fBHyString\fPs that are not produced by bracket strings have their \fBbrackets\fP set to \fBNone\fP\&. .SS HyBytes .sp \fBhy.models.HyBytes\fP is like \fBHyString\fP, but for sequences of bytes. It inherits from \fBbytes\fP\&. .SS Numeric Models .sp \fBhy.models.HyInteger\fP represents integer literals, using the \fBint\fP type. .sp \fBhy.models.HyFloat\fP represents floating\-point literals. .sp \fBhy.models.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.HySymbol\fP is the model used to represent symbols in the Hy language. Like \fBHyString\fP, it inherits from \fBstr\fP (or \fBunicode\fP on Python 2). .sp Symbols are mangled when they are compiled to Python variable names. .SS HyKeyword .sp \fBhy.models.HyKeyword\fP represents keywords in Hy. Keywords are symbols starting with a \fB:\fP\&. See syntax\-keywords\&. .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 reconfigure 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: _temp_name_here = True else: _temp_name_here = False print(_temp_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(do (setv 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 \fBobscure\-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] (setv g (gensym)) \(ga(do (setv ~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 \fBsetv\fP form: .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 (do (setv 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(do (setv ~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(do (setv ~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 EXTRA MODULES INDEX .sp These modules are considered no less stable than Hy\(aqs built\-in functions and macros, but they need to be loaded with \fB(import \&...)\fP or \fB(require ...)\fP\&. .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\%https://en.wikipedia.org/wiki/Anaphoric_macro\fP) .UNINDENT .UNINDENT .sp To use these macros you need to require the \fBhy.extra.anaphoric\fP module like so: .sp \fB(require [hy.extra.anaphoric [*]])\fP .sp These macros are implemented by replacing any use of the designated anaphoric symbols (\fBit\fP, in most cases) with a gensym. Consequently, it\(aqs unwise to nest these macros where symbol replacement is happening. Symbol replacement typically takes place in \fBbody\fP or \fBform\fP parameters, where the output of the expression may be returned. It is also recommended to avoid using an affected symbol as something other than a variable name, as in \fB(print "My favorite Stephen King book is" \(aqit)\fP\&. .SS ap\-if .sp Usage: \fB(ap\-if test\-form then\-form else\-form)\fP .sp As if, but the result of the test form is named \fBit\fP in the subsequent forms. As with \fBif\fP, the else\-clause is optional. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import os) => (ap\-if (.get os.environ "PYTHONPATH") \&... (print "Your PYTHONPATH is" it)) .ft P .fi .UNINDENT .UNINDENT .SS ap\-each .sp Usage: \fB(ap\-each xs body…)\fP .sp Evaluate the body forms for each element \fBit\fP of \fBxs\fP and return \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (ap\-each [1 2 3] (print it)) 1 2 3 .ft P .fi .UNINDENT .UNINDENT .SS ap\-each\-while .sp Usage: \fB(ap\-each\-while xs pred body…)\fP .sp As \fBap\-each\fP, but the form \fBpred\fP is run before the body forms on each iteration, and the loop ends if \fBpred\fP is false. .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 xs)\fP .sp Create a generator like \fI\%map()\fP that yields each result of \fBform\fP evaluated with \fBit\fP bound to successive elements of \fBxs\fP\&. .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 xs)\fP .sp As \fBap\-map\fP, but the predicate function \fBpredfn\fP (yes, that\(aqs a function, not an anaphoric form) is applied to each \fBit\fP, and the anaphoric mapping form \fBrep\fP is only applied if the predicate is true. Otherwise, \fBit\fP is yielded unchanged. .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 xs)\fP .sp The \fI\%filter()\fP equivalent of \fBap\-map\fP\&. .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 xs)\fP .sp Equivalent to \fB(ap\-filter (not form) xs)\fP\&. .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 Equivalent to \fB(ap\-each (range n) body…)\fP\&. .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 form xs)\fP .sp Evaluate the predicate \fBform\fP for each element \fBit\fP of \fBxs\fP\&. When the predicate is true, stop and return \fBit\fP\&. If the predicate is never true, return \fBNone\fP\&. .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 form list)\fP .sp Evaluate the predicate \fBform\fP for every element \fBit\fP of \fBxs\fP\&. Return the last element for which the predicate is true, or \fBNone\fP if there is no such element. .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 xs &optional initial\-value)\fP .sp This macro is an anaphoric version of \fBreduce()\fP\&. It works as follows: .INDENT 0.0 .IP \(bu 2 Bind \fBacc\fP to the first element of \fBxs\fP, bind \fBit\fP to the second, and evaluate \fBform\fP\&. .IP \(bu 2 Bind \fBacc\fP to the result, bind \fBit\fP to the third value of \fBxs\fP, and evaluate \fBform\fP again. .IP \(bu 2 Bind \fBacc\fP to the result, and continue until \fBxs\fP is exhausted. .UNINDENT .sp If \fBinitial\-value\fP is supplied, the process instead begins with \fBacc\fP set to \fBinitial\-value\fP and \fBit\fP set to the first element of \fBxs\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (ap\-reduce (+ it acc) (range 10)) 45 .ft P .fi .UNINDENT .UNINDENT .SS #% .sp Usage: \fB#% expr\fP .sp Makes an expression into a function with an implicit \fB%\fP parameter list. .sp A \fB%i\fP symbol designates the (1\-based) \fIi\fP th parameter (such as \fB%3\fP). Only the maximum \fB%i\fP determines the number of \fB%i\fP parameters\-\-the others need not appear in the expression. \fB%*\fP and \fB%**\fP name the \fB&rest\fP and \fB&kwargs\fP parameters, respectively. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (#%[%1 %6 42 [%2 %3] %* %4] 1 2 3 4 555 6 7 8) [1, 6, 42, [2, 3], (7, 8), 4] => (#% %** :foo 2) {"foo": 2} .ft P .fi .UNINDENT .UNINDENT .sp When used on an s\-expression, \fB#%\fP is similar to Clojure\(aqs anonymous function literals\-\-\fB#()\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (setv add\-10 #%(+ 10 %1)) => (add\-10 6) 16 .ft P .fi .UNINDENT .UNINDENT .sp \fB#%\fP determines the parameter list by the presence of a \fB%*\fP or \fB%**\fP symbol and by the maximum \fB%i\fP symbol found \fIanywhere\fP in the expression, so nesting of \fB#%\fP forms is not recommended. .SS Reserved Names .SS names .sp Usage: \fB(names)\fP .sp This function can be used to get a list (actually, a \fBfrozenset\fP) of the names of Hy\(aqs built\-in functions, macros, and special forms. The output also includes all Python reserved words. All names are in unmangled form (e.g., \fBnot\-in\fP rather than \fBnot_in\fP). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import hy.extra.reserved) => (in "defclass" (hy.extra.reserved.names)) True .ft P .fi .UNINDENT .UNINDENT .SH CONTRIBUTOR MODULES INDEX .sp These modules are experimental additions to Hy. Once deemed mature, they will be moved to the \fBhy.extra\fP namespace or loaded by default. .sp Contents: .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\%https://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 raised. .sp Usage: \fB(loop bindings &rest body)\fP .sp Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require [hy.contrib.loop [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 Profile .sp New in version 0.10.0. .sp The \fBprofile\fP macros make it easier to find bottlenecks. .SS Macros .SS profile/calls .sp \fBprofile/calls\fP allows you to create a call graph visualization. \fBNote:\fP You must have \fI\%Graphviz\fP installed for this to work. .sp Usage: \fI(profile/calls (body))\fP .sp Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require [hy.contrib.profile [profile/calls]]) (profile/calls (print "hey there")) .ft P .fi .UNINDENT .UNINDENT .SS profile/cpu .sp \fBprofile/cpu\fP allows you to profile a bit of code. .sp Usage: \fI(profile/cpu (body))\fP .sp Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require [hy.contrib.profile [profile/cpu]]) (profile/cpu (print "hey there")) .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C hey there 2 function calls in 0.000 seconds Random listing order was used ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 {method \(aqdisable\(aq of \(aq_lsprof.Profiler\(aq objects} 1 0.000 0.000 0.000 0.000 {print} .ft P .fi .UNINDENT .UNINDENT .SS Lazy sequences .sp New in version 0.12.0. .sp The sequences module contains a few macros for declaring sequences that are evaluated only as much as the client code requires. Unlike generators, they allow accessing the same element multiple times. They cache calculated values, and the implementation allows for recursive definition of sequences without resulting in recursive computation. .sp To use these macros, you need to require them and import some other names like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (require [hy.contrib.sequences [defseq seq]]) (import [hy.contrib.sequences [Sequence end\-sequence]]) .ft P .fi .UNINDENT .UNINDENT .sp The simplest sequence can be defined as \fB(seq [n] n)\fP\&. This defines a sequence that starts as \fB[0 1 2 3 ...]\fP and continues forever. In order to define a finite sequence, you need to call \fBend\-sequence\fP to signal the end of the sequence: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (seq [n] "sequence of 5 integers" (cond [(< n 5) n] [True (end\-sequence)])) .ft P .fi .UNINDENT .UNINDENT .sp This creates the following sequence: \fB[0 1 2 3 4]\fP\&. For such a sequence, \fBlen\fP returns the amount of items in the sequence and negative indexing is supported. Because both of these require evaluating the whole sequence, calling one on an infinite sequence would take forever (or at least until available memory has been exhausted). .sp Sequences can be defined recursively. For example, the Fibonacci sequence could be defined as: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defseq fibonacci [n] "infinite sequence of fibonacci numbers" (cond [(= n 0) 0] [(= n 1) 1] [True (+ (get fibonacci (\- n 1)) (get fibonacci (\- n 2)))])) .ft P .fi .UNINDENT .UNINDENT .sp This results in the sequence \fB[0 1 1 2 3 5 8 13 21 34 ...]\fP\&. .SS seq .sp Usage: \fB(seq [n] (* n n))\fP .sp Creates a sequence defined in terms of \fBn\fP\&. .SS defseq .sp Usage: \fB(defseq numbers [n] n)\fP .sp Creates a sequence defined in terms of \fBn\fP and assigns it to a given name. .SS end\-sequence .sp Usage: \fB(seq [n] (if (< n 5) n (end\-sequence)))\fP .sp Signals the end of a sequence when an iterator reaches the given point of the sequence. Internally, this is done by raising \fBIndexError\fP, catching that in the iterator, and raising \fBStopIteration\fP\&. .SS walk .sp New in version 0.11.0. .SS Functions .SS walk .sp Usage: \fI(walk inner outer form)\fP .sp \fBwalk\fP traverses \fBform\fP, an arbitrary data structure. Applies \fBinner\fP to each element of form, building up a data structure of the same type. Applies \fBouter\fP to the result. .sp Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import [hy.contrib.walk [walk]]) => (setv a \(aq(a b c d e f)) => (walk ord identity a) HyExpression([ 97, 98, 99, 100, 101, 102]) => (walk ord first a) 97 .ft P .fi .UNINDENT .UNINDENT .SS postwalk .sp Usage: \fI(postwalk f form)\fP .sp Performs depth\-first, post\-order traversal of \fBform\fP\&. Calls \fBf\fP on each sub\-form, uses \fBf\fP \(aqs return value in place of the original. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import [hy.contrib.walk [postwalk]]) => (setv trail \(aq([1 2 3] [4 [5 6 [7]]])) => (defn walking [x] \&... (print "Walking:" x :sep "\en") \&... x) => (postwalk walking trail) Walking: 1 Walking: 2 Walking: 3 Walking: HyExpression([ HyInteger(1), HyInteger(2), HyInteger(3)]) Walking: 4 Walking: 5 Walking: 6 Walking: 7 Walking: HyExpression([ HyInteger(7)]) Walking: HyExpression([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])]) Walking: HyExpression([ HyInteger(4), HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])])]) Walking: HyExpression([ HyList([ HyInteger(1), HyInteger(2), HyInteger(3)]), HyList([ HyInteger(4), HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])])])]) HyExpression([ HyList([ HyInteger(1), HyInteger(2), HyInteger(3)]), HyList([ HyInteger(4), HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])])])]) .ft P .fi .UNINDENT .UNINDENT .SS prewalk .sp Usage: \fI(prewalk f form)\fP .sp Performs depth\-first, pre\-order traversal of \fBform\fP\&. Calls \fBf\fP on each sub\-form, uses \fBf\fP \(aqs return value in place of the original. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (import [hy.contrib.walk [prewalk]]) => (setv trail \(aq([1 2 3] [4 [5 6 [7]]])) => (defn walking [x] \&... (print "Walking:" x :sep "\en") \&... x) => (prewalk walking trail) Walking: HyExpression([ HyList([ HyInteger(1), HyInteger(2), HyInteger(3)]), HyList([ HyInteger(4), HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])])])]) Walking: HyList([ HyInteger(1), HyInteger(2), HyInteger(3)]) Walking: 1 Walking: 2 Walking: 3 Walking: HyList([ HyInteger(4), HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])])]) Walking: 4 Walking: HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])]) Walking: 5 Walking: 6 Walking: HyList([ HyInteger(7)]) Walking: 7 HyExpression([ HyList([ HyInteger(1), HyInteger(2), HyInteger(3)]), HyList([ HyInteger(4), HyList([ HyInteger(5), HyInteger(6), HyList([ HyInteger(7)])])])]) .ft P .fi .UNINDENT .UNINDENT .SS macroexpand\-all .sp Usage: \fI(macroexpand\-all form &optional module\-name)\fP .sp Recursively performs all possible macroexpansions in form, using the \fBrequire\fP context of \fBmodule\-name\fP\&. \fImacroexpand\-all\fP assumes the calling module\(aqs context if unspecified. .SS Macros .SS let .sp \fBlet\fP creates lexically\-scoped names for local variables. A let\-bound name ceases to refer to that local outside the \fBlet\fP form. Arguments in nested functions and bindings in nested \fBlet\fP forms can shadow these names. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (let [x 5] ; creates a new local bound to name \(aqx \&... (print x) \&... (let [x 6] ; new local and name binding that shadows \(aqx \&... (print x)) \&... (print x)) ; \(aqx refers to the first local again 5 6 5 .ft P .fi .UNINDENT .UNINDENT .sp Basic assignments (e.g. \fBsetv\fP, \fB+=\fP) will update the local variable named by a let binding, when they assign to a let\-bound name. .sp But assignments via \fBimport\fP are always hoisted to normal Python scope, and likewise, \fBdefclass\fP will assign the class to the Python scope, even if it shares the name of a let binding. .sp Use \fBimportlib.import_module\fP and \fBtype\fP (or whatever metaclass) instead, if you must avoid this hoisting. .sp The \fBlet\fP macro takes two parameters: a list defining \fIvariables\fP and the \fIbody\fP which gets executed. \fIvariables\fP is a vector of variable and value pairs. .sp Like the \fBlet*\fP of many other Lisps, \fBlet\fP executes the variable assignments one\-by\-one, in the order written: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&.. code\-block:: hy .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 => (let [x 5 \&... y (+ x 1)] \&... (print x y)) 5 6 .UNINDENT .UNINDENT .sp Unlike them, however, each \fB(let …)\fP form uses only one namespace for all its assignments. Thus, \fB(let [x 1 x (fn [] x)] (x))\fP returns a function object, not 1 as you might expect. .sp It is an error to use a let\-bound name in a \fBglobal\fP or \fBnonlocal\fP form. .SS Hy representations .sp New in version 0.13.0. .sp \fBhy.contrib.hy\-repr\fP is a module containing two functions. To import them, say: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (import [hy.contrib.hy\-repr [hy\-repr hy\-repr\-register]]) .ft P .fi .UNINDENT .UNINDENT .sp To make the Hy REPL use it for output, invoke Hy like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ hy \-\-repl\-output\-fn=hy.contrib.hy\-repr.hy\-repr .ft P .fi .UNINDENT .UNINDENT .SS hy\-repr .sp Usage: \fB(hy\-repr x)\fP .sp This function is Hy\(aqs equivalent of Python\(aqs built\-in \fBrepr\fP\&. It returns a string representing the input object in Hy syntax. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (hy\-repr [1 2 3]) \(aq[1 2 3]\(aq => (repr [1 2 3]) \(aq[1, 2, 3]\(aq .ft P .fi .UNINDENT .UNINDENT .sp Like \fBrepr\fP in Python, \fBhy\-repr\fP can round\-trip many kinds of values. Round\-tripping implies that given an object \fBx\fP, \fB(eval (read\-str (hy\-repr x)))\fP returns \fBx\fP, or at least a value that\(aqs equal to \fBx\fP\&. .SS hy\-repr\-register .sp Usage: \fB(hy\-repr\-register the\-type fun)\fP .sp \fBhy\-repr\-register\fP lets you set the function that \fBhy\-repr\fP calls to represent a type. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C => (defclass C) => (hy\-repr\-register C (fn [x] "cuddles")) => (hy\-repr [1 (C) 2]) \(aq[1 cuddles 2]\(aq .ft P .fi .UNINDENT .UNINDENT .sp If the type of an object passed to \fBhy\-repr\fP doesn\(aqt have a registered function, \fBhy\-repr\fP will search the type\(aqs method resolution order (its \fB__mro__\fP attribute) for the first type that does. If \fBhy\-repr\fP doesn\(aqt find a candidate, it falls back on \fBrepr\fP\&. .sp Registered functions often call \fBhy\-repr\fP themselves. \fBhy\-repr\fP will automatically detect self\-references, even deeply nested ones, and output \fB"..."\fP for them instead of calling the usual registered function. To use a placeholder other than \fB"..."\fP, pass a string of your choice to the keyword argument \fB:placeholder\fP of \fBhy\-repr\-register\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C (defclass Container [object] (defn __init__ (fn [self value] (setv self.value value)))) (hy\-repr\-register Container :placeholder "HY THERE" (fn [x] (+ "(Container " (hy\-repr x.value) ")"))) (setv container (Container 5)) (setv container.value container) (print (hy\-repr container)) ; Prints "(Container HY THERE)" .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\%pytest\fP\&. .sp To run the tests: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pytest .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 Contributor Guidelines .sp Contributions are welcome and greatly appreciated. Every little bit helps in making Hy better. Potential contributions include: .INDENT 0.0 .IP \(bu 2 Reporting and fixing bugs. .IP \(bu 2 Requesting features. .IP \(bu 2 Adding features. .IP \(bu 2 Writing tests for outstanding bugs or untested features. \- You can mark tests that Hy can\(aqt pass yet as \fI\%xfail\fP\&. .IP \(bu 2 Cleaning up the code. .IP \(bu 2 Improving the documentation. .IP \(bu 2 Answering questions on \fI\%the IRC channel\fP, \fI\%the mailing list\fP, or \fI\%Stack Overflow\fP\&. .IP \(bu 2 Evangelizing for Hy in your organization, user group, conference, or bus stop. .UNINDENT .SS Issues .sp In order to report bugs or request features, search the \fI\%issue tracker\fP to check for a duplicate. (If you\(aqre reporting a bug, make sure you can reproduce it with the very latest, bleeding\-edge version of Hy from the \fBmaster\fP branch on GitHub. Bugs in stable versions of Hy are fixed on \fBmaster\fP before the fix makes it into a new stable release.) If there aren\(aqt any duplicates, then you can make a new issue. .sp It\(aqs totally acceptable to create an issue when you\(aqre unsure whether something is a bug or not. We\(aqll help you figure it out. .sp Use the same issue tracker to report problems with the documentation. .SS Pull requests .sp Submit proposed changes to the code or documentation as pull requests (PRs) on \fI\%GitHub\fP\&. Git can be intimidating and confusing to the uninitiated. \fI\%This getting\-started guide\fP may be helpful. However, if you\(aqre overwhelmed by Git, GitHub, or the rules below, don\(aqt sweat it. We want to keep the barrier to contribution low, so we\(aqre happy to help you with these finicky things or do them for you if necessary. .SS Deciding what to do .sp Issues tagged \fI\%good\-first\-bug\fP are expected to be relatively easy to fix, so they may be good targets for your first PR for Hy. .sp If you\(aqre proposing a major change to the Hy language, or you\(aqre unsure of the proposed change, create an issue to discuss it before you write any code. This will allow others to give feedback on your idea, and it can avoid wasted work. .SS File headers .sp Every Python or Hy file in the source tree that is potentially copyrightable should have the following header (but with \fB;;\fP in place of \fB#\fP for Hy files): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Copyright [current year] the authors. # This file is part of Hy, which is free software licensed under the Expat # license. See the LICENSE. .ft P .fi .UNINDENT .UNINDENT .sp As a rule of thumb, a file can be considered potentially copyrightable if it includes at least 10 lines that contain something other than comments or whitespace. If in doubt, include the header. .SS Commit formatting .sp Many PRs are small enough that only one commit is necessary, but bigger ones should be organized into logical units as separate commits. PRs should be free of merge commits and commits that fix or revert other commits in the same PR (\fBgit rebase\fP is your friend). .sp Avoid committing spurious whitespace changes. .sp The first line of a commit message should describe the overall change in 50 characters or less. If you wish to add more information, separate it from the first line with a blank line. .SS Testing .sp New features and bug fixes should be tested. If you\(aqve caused an \fI\%xfail\fP test to start passing, remove the xfail mark. If you\(aqre testing a bug that has a GitHub issue, include a comment with the URL of the issue. .sp No PR may be merged if it causes any tests to fail. You can run the test suite and check the style of your code with \fBmake d\fP\&. The byte\-compiled versions of the test files can be purged using \fBgit clean \-dfx tests/\fP\&. If you want to run the tests while skipping the slow ones in \fBtest_bin.py\fP, use \fBpytest \-\-ignore=tests/test_bin.py\fP\&. .SS NEWS and AUTHORS .sp If you\(aqre making user\-visible changes to the code, add one or more items describing it to the NEWS file. .sp Finally, add yourself to the AUTHORS file (as a separate commit): you deserve it. :) .SS The PR itself .sp PRs should ask to merge a new branch that you created for the PR into hylang/hy\(aqs \fBmaster\fP branch, and they should have as their origin the most recent commit possible. .sp If the PR fulfills one or more issues, then the body text of the PR (or the commit message for any of its commits) should say "Fixes #123" or "Closes #123" for each affected issue number. Use this exact (case\-insensitive) wording, because when a PR containing such text is merged, GitHub automatically closes the mentioned issues, which is handy. Conversely, avoid this exact language if you want to mention an issue without closing it (because e.g. you\(aqve partly but not entirely fixed a bug). .sp There are two situations in which a PR is allowed to be merged: .INDENT 0.0 .IP 1. 3 When it is approved by \fBtwo\fP members of Hy\(aqs core team other than the PR\(aqs author. Changes to the documentation, or trivial changes to code, need only \fBone\fP approving member. .IP 2. 3 When the PR is at least \fBtwo weeks\fP old and \fBno\fP member of the Hy core team has expressed disapproval of the PR in its current state. (Exception: a PR to create a new release is not eligible to be merged under this criterion, only the first one.) .UNINDENT .sp Anybody on the Hy core team may perform the merge. Merging should create a merge commit (don\(aqt squash unnecessarily, because that would remove separation between logically separate commits, and don\(aqt fast\-forward, because that would throw away the history of the commits as a separate branch), which should include the PR number in the commit message. .SS Contributor Code of Conduct .sp As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. .sp We are committed to making participation in this project a harassment\-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. .sp Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. .sp Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. .sp This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. .sp Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. .sp This Code of Conduct is adapted from the \fI\%Contributor Covenant\fP, version 1.1.0, available at \fI\%http://contributor\-covenant.org/version/1/1/0/\fP\&. .SS Core Team .sp The core development team of Hy consists of following developers: .INDENT 0.0 .IP \(bu 2 \fI\%Kodi B. Arfer\fP .IP \(bu 2 \fI\%Nicolas Dandrimont\fP .IP \(bu 2 \fI\%Julien Danjou\fP .IP \(bu 2 \fI\%Rob Day\fP .IP \(bu 2 \fI\%Simon Gomizelj\fP .IP \(bu 2 \fI\%Ryan Gonzalez\fP .IP \(bu 2 \fI\%Abhishek Lekshmanan\fP .IP \(bu 2 \fI\%Morten Linderud\fP .IP \(bu 2 \fI\%Matthew Odendahl\fP .IP \(bu 2 \fI\%Paul Tagliamonte\fP .IP \(bu 2 \fI\%Brandon T. Willard\fP .UNINDENT .SH AUTHOR unknown .SH COPYRIGHT 2020 the authors .\" Generated by docutils manpage writer. .