Last active
August 17, 2017 18:43
-
-
Save woodrush/41f3e0ab35c129c2a54b3ee804bec377 to your computer and use it in GitHub Desktop.
Scala-style placeholder functions in Hy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Same, but with macros | |
(defmacro pm [expr &rest args] | |
(defn _listlike? [l] | |
(or | |
(= hy.models.HyList (type l)) | |
(= hy.models.HyExpression (type l)) | |
(= list (type l)))) | |
(defn _recursive-count [l] | |
(if (_listlike? l) | |
(sum (map _recursive-count l)) | |
(if (= '_ l) 1 0))) | |
(defn _recursive-replace [l iter] | |
(if (_listlike? l) | |
`(~@(map (fn [x] (_recursive-replace x iter)) l)) | |
(if (= '_ l) (next iter) l))) | |
(_recursive-replace expr (iter args))) | |
(pm (print _ '(_ (_ _)_) _) 1 2 3 4 5 6) | |
; ==> 1 (2 (3 4) 5) 6 | |
;;; The previous #p outputs something like | |
;;; (#p(print _ '(_ (_ _)_)) 1 2 3 4 5) | |
;;; ==> 1 (':G_1244' (':G_1245' ':G_1246') ':G_1247') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Create anonymous functions using _ as a placeholder | |
;;; Example: | |
;;; (#_(* _ (+ _ 12) _) 1 2 3) | |
;;; ==> 42 | |
(defn _listlike? [l] | |
(or | |
(= hy.models.HyList (type l)) | |
(= hy.models.HyExpression (type l)) | |
(= list (type l)))) | |
(defn recursive-count [l] | |
(if (_listlike? l) | |
(sum (map recursive-count l)) | |
(if (= '_ l) 1 0))) | |
(defn recursive-replace [l iter] | |
(if (_listlike? l) | |
`(~@(map (fn [x] (recursive-replace x iter)) l)) | |
(if (= '_ l) (next iter) l))) | |
(deftag p [body] | |
(setv argslist (list-comp (gensym) [x (range (recursive-count body))])) | |
`(fn [~@argslist] ~(recursive-replace body (iter argslist)))) | |
(print (#p(* _ (+ _ 12) _) 1 2 3)) | |
; ==> 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment