Skip to content

Instantly share code, notes, and snippets.

@rduplain
Last active December 22, 2020 06:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduplain/dfc809198e102981da1e to your computer and use it in GitHub Desktop.
Save rduplain/dfc809198e102981da1e to your computer and use it in GitHub Desktop.
Getting started with hy (hylang.org), a simple example.
#!/usr/bin/env hy
;; match.hy - Getting started with hy (hylang.org), a simple example.
;;
;; As executable, `chmod +x match.hy`:
;;
;; $ ./match.hy '(.*), (.*)!' 'Hello, world!'
;; ('Hello', 'world')
;;
;; Developed on hy master 14c412c (after 0.11.1) on Python 3.5.
;;
;; $ pip install git+https://git@github.com/hylang/hy.git@14c412c#egg=hy
;;
;; To use within Python:
;;
;; $ python
;; >>> import hy # Prerequisite to import a .hy file.
;; >>> import match
;; >>> match.match('(.*), (.*)!')('Hello, world!')
;; ('Hello', 'world')
(require hy.contrib.anaphoric)
(import re)
(defn match [pattern]
"match :: pattern => (string => tuple), tuple of groups matching pattern."
(let [pattern_re (.compile re pattern)]
(fn [x]
(ap-if (.match pattern_re x)
(.groups it)
(,)))))
(defn test-match []
(defn test [matcher arg expected]
(let [msg (.format "{} => {}" arg expected)]
(assert (= expected (matcher arg)) msg)))
(let [matcher (match "Hello, (.*)!")]
(test matcher "Hello" (,))
(test matcher "Hello, world!" (, "world")))
(let [matcher (match "\((\d), (\d)\)")]
(test matcher "()" (,))
(test matcher "(7, 8)" (, "7" "8"))))
(defmain [prog pattern x &rest args]
(test-match)
(print ((match pattern) x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment