User:Owittnan/sandbox/A Little Hy Primer

Welcome to A Little Hy Primer. Much like A Little C Primer, this is a novice introduction to the Hy programming language. This text will assume some familiarity with Python and at least a basic level of familiarity with a Lisp.

Installation

edit

To install Hy, you first need Python and Pip installed. There are many guides online about how to do this.

Once you have Python and Pip installed, run pip install --pre --user hy. This will install hy from the PyPI package repository.

You can also use the online interpreter.

With that, let's get started.

Hello world

edit

The first program you run in any programming language is the "Hello world" program. So let's do just that. Open up a file and type this in:

(print "hello, world")

Make sure to save the file with the .hy extension (not needed in the interpreter). If using the interpreter, click the Run button in the top right of the editor. If not, open a console in the same directory as your .hy file and run hy <filename>.hy, replacing <filename> with the name of the .hy file.

You should see hello, world printed in the console/output box.

Basic operations

edit

Hy can do arithmetic operations. It uses the prefix notation:

(+ 1 1) ; -> 2 (comments start with semicolons)
(- 3 2) ; -> 1
(/ 8 2) ; -> 4
(* 3 3) ; -> 9
(** 3 2) ; -> 9
(- (* (+ 1 3 88) 2) 8) ; -> 176 -- equivalent to ((1 + 3 + 88) * 2) - 8 in infix notation

It also has the standard if conditional operator, but with a more lispy syntax:

(if condition
  true-statement
  false-statement)

The above is the same as if-else in Python. To have elifs you use the cond macro:

(cond [condition-1 statement-1]
      [condition-2 statement-2]
      [condition-3 statement-3]))
; equivalent to:
; (if condition-1
;     statement-1
;     (if condition-2
;         statement-2
;         (if condition-3
;             statement-3)))

and to execute more than one statement in an if you need a do-block:

(if condition-1
    (do
      (thing-1)
      (thing-2))
    (do
      (other-thing-1)
      (other-thing-2)))

There are also macros for if you only want the true or false statement:

(when condition-1 ; = (if conditional (do statement))
   statement-1)

(unless condition-2 ; = (if conditional None (do statement))
   statement-2)