Does Hy code require indenting, just like Python?

118 Views Asked by At

I am unable to submit multiple lines of Hy to Python without indentation:

import hy
expr=hy.read_str("(+ 1 1)(+ 2 2)")
hy.eval(expr)
=> 2

The second '(+ 2 2)' statement has apparently been ignored.

Obviously Python's raison d'etre is indentation, and of course the 'Hy Style Guide" shows everything constantly indented, and has this to say as well:

"New lines must ALWAYS be indented past their parent opening bracket."

So is there no way to avoid indentation in Hy and to submit a single, non-indented string via hy.eval(expr)?

2

There are 2 best solutions below

0
On BEST ANSWER

Hy is a free-form language, like most programming languages and unlike Python. The style guide is only a style guide.

What you're seeing with read-str is issue #1591. Use do to combine multiple expressions into one.

2
On

No, indentation is not required in Hy, and (as Kodiologist notes) the Hy Style Guide's endless prattling on about indentation is, as it should be, nothing more than a suggestion.

However Hy does not have any sort of 'compound expression'-type of form, and the submission of a sequence of multiple statements to Hy does require additional tricks.

The obvious solution, to make submit multiple statements (aka 'forms') as a sequence does NOT work:

hy.eval(hy.read_str( "((+ 1 1) (+ 2 2))" ))
-> TypeError: 'int' object is not callable

Which occurs of course because Hy is trying to 'call' the number 2 as a function on the number 4.

One can collect sequences of forms in a list. However this captures all of their outputs:

hy.eval(hy.read_str( "[(+ 1 1) (+ 2 2)]" ))
-> [ 2 4 ]

Naturally for a very large computation with many steps it is possible to end up with a list of junk that one does not need, wasting memory. (However most Hy forms resolve to 'None' which is pretty small). So one can just wrap everything with a 'last' statement:

hy.eval(hy.read_str( "(last [(+ 1 1) (+ 2 2) (+ 3 3)] )" ))
-> 6

Probably the best solution is to use do as Kodiologist notes:

hy.eval(hy.read_str( "(do (+ 1 1) (+ 2 2) (+ 3 3) )" ))
-> 6