Skip to content

Instantly share code, notes, and snippets.

@rduplain
Last active Dec 22, 2020
Embed
What would you like to do?
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