Hy a deeper look

1 A more thorough look at hy

I introduced hy recently, let's have a bit more of a deeper look into it. Check out the previous post to learn some of the syntax, Here

I like the parens, but it is not everybodies taste, but do try hy even in spite of this.

1.1 Import

First let me introduce the importing of modules, since the syntax here is a bit different

(import os)

This is all normal nothing fancy here, but how do we use from X import Y?

(import beem [Hive])

This is how that is done, you can also use dots in the first name as in.

(import beem.account [Account])

making it totally equal to python.

1.2 Loops

In python there are several loops, and even though lisps often use recursion, I do not think python's vm is very good for recursion, sort of the same problem clojure faced, but you can just use loops in python instead. So there are a few loops available in hy, the same ones in python, unless you want to write your own.

(setv a [1 2 3 4 5])
(for [item a]
  (print (* item item)))

Obvious this can be shorter by replacing a with the literal definition of a in the loop.

1.2.1 While Loop

You can use all the loops python has in hy while loops are also available

(setv x 0)
(while (> 10 x)
  (print x)
  (setv x (+ 1 x)))

1.3 Functional Style programming

These makes some stuff very simple to do, no need to do a loop or anything, just do a single function that does what you want, and that is it apply it to the list.

1.3.1 Filter

(for [item (filter (fn [x] (= (% x 2) 0)) (range 10))]
  (print item))

pretty much a pointless example, since I am sure we can use something else to do this instead, but then this is just for illustration as to how filter works, and this is the simplest example I can think of.

1.3.2 Map

(for [item (map (fn [x] (* 2 x)) (range 10))]
  (print item))

1.4 Arrow

So this is a funky thing hy has.

(-> "Hello World   " (.strip) (.split))

This is pretty cool, the arrow kind of works a bit like the pipe in unix shell so essentially this transforms into

(.split (.strip "Hello World   "))

I really like the arrow notation much better.

There is another arrow, which operates a bit differently

(setv a (-> 4 (- 2) (+ 1)))
(setv b (->> 4 (- 2) (+ 1)))
(return [a b])

The first expression returns 3, but the second returns -1. The first expression would transform to

(+ (- 4 2) 1)

That is as we saw above, no problems, now lets look at the other arrow. The second expression would transform into

(+ 1 (- 2 4))

pretty wild stuff.

There very easily could be more cool stuff in hy, but that will have to wait for another post.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Ecency