SlideShare a Scribd company logo
Метапрограммирование в CL
 "Lisp isn't a language, it's a building material."
                                       - Alan Kay




          ● Макросы
          ● Макросы чтения

          ● Макросы компилятора

          ● ...
Квазицитирование
(defmacro nif (expr positive zero negative)
    (let ((var (gensym)))
          `(let ((,var ,expr))
               (cond
                     ((plusp ,var) ,positive)
                     ((zerop ,var) ,zero)
                     (t ,negative)))))

(nif (- (* b b) (* 4 a c))
      2
      1
      0)

(LET ((#:G624 (- (* B B) (* 4 A C))))
 (COND ((PLUSP #:G624) 2) ((ZEROP #:G624) 1) (T 0)))
Анафорические макросы
(defmacro aif (condition then &optional else)
    `(let ((it ,condition))
         (if it
                ,then
                ,else)))

(aif (load-data))
      (pprint it)
      (print "No data loaded."))

awhen, awhile, aand, alambda...

(aand
    (load-data)
    (take-field it)
    (do-smth it))
Декораторы
(defmacro defun/decorated ((&rest decorator) name (&rest params)
                                     &body body)
    `(defun ,name (,@params)
             (,@decorator
                 (lambda () ,@body)
                 ,@params)))

(defun decorator (x f &rest params)
    (format t "decorator ~A ~{~A ~}" x params)
    (funcall f))

(defun/decorated
    (decorator "smth")
    square (x)
             (* x x))
Макросы пишут макросы: TCO
     (defun fact (n acc)
         (if (zerop n)
                   acc
                   (fact (- n 1) (* n acc))))

     (defmacro defun/tco (name (&rest params) &body body)
         `(defun ,name (,@params)
                  (macrolet ((,name (&rest args)
                     `(progn
                          (psetq
                               ,@(mapcan (lambda (p v)
                                   (list p v))
                                   ',params args))
                          (go :label))))
                     (tagbody
                          :label
                          (return-from ,name (progn ,@body))))))

     (defun/tco fact/tco (n acc)
         (if (zerop n)
                   acc
                   (fact/tco (- n 1) (* n acc))))
EDSL
● CLOS (Common Lisp Object System)
● ITERATE




    (iter (for i from 1)
          (for a in some-list)
          (collect (cons i a)))

● ContextL (AOP)
● Chtml-matcher



(<tbody nil
   (tr nil (<a ((name ?post-num)))
      (tr nil)
      (tr nil (?post-body <div ((id "post_message_?"))))))
Макросы чтения
(set-dispatch-macro-character ## #$
   #'(lambda (stream char arg)
       (parse-integer (coerce
          (loop
               for ch = (peek-char nil stream nil nil t)
               while (or (digit-char-p ch) (eql ch #_))
               do (read-char stream t nil t)
               if (digit-char-p ch)
                   collect ch)
          'string))))

#$1_000_000
Макросы чтения
(let ((foo 1))
    #Uhttp://www.example.com/widget/{foo}/parts)

"http://www.example.com/widget/1/parts"


(uri-template-bind (#Uhttp://www.example.com/{part}/{number})
    "http://www.example.com/widget/1"
 (list part (parse-integer number) %uri-host))

("widget" 1 "www.example.com")
Макросы чтения
(set-dispatch-macro-character ## #/
   (lambda (stream char arg)
       (let ((pattern (coerce
               (loop
                    for ch = (read-char stream t nil t)
                    until (eql ch #/)
                    collect ch)
               'string)))
           `(lambda (&rest args)
               (apply #'cl-ppcre:scan ,pattern args)))))

          (#/[a-z]+/ str)

          ((lambda (&rest args)
              (apply #'cl-ppcre:scan "[a-z]+" args)) str)

          (cl-ppcre:scan "[a-z]+" str)
Макросы компилятора
(format stream control-string arg1...)

(funcall (formatter control-string) stream arg1 ...)

(lambda (stream &rest arguments)
    (apply #'format stream control-string arguments))

(formatter "Hello, ~A")

(LAMBDA (STREAM #:FORMAT-ARG633)
   (WRITE-STRING "Hello, " STREAM)
   (PRINC #:FORMAT-ARG633 STREAM))

(formatter "~{~A~%~}")

(LAMBDA (STREAM #:FORMAT-ARG636)
   (LET ((ARGS #:FORMAT-ARG636))
       (LOOP
           (WHEN (NULL ARGS) (RETURN))
           (PRINC (POP ARGS) STREAM)
           (TERPRI STREAM))))
Макросы компилятора
                                      CL-PPCRE
(define-compiler-macro scan (&whole form
                                 &environment env
                                 regex target-string
                                 &rest rest)
    (cond
         ((constantp regex env)
               `(scan (load-time-value (create-scanner ,regex)) ,target-string ,@rest))
         (t form)))
Ссылки
● Paul Graham «On Lisp» http://www.paulgraham.com/onlisp.html
● Doug Hoyte «LOL» http://letoverlambda.com/

● CL-PPCRE http://weitz.de/cl-ppcre/

● Iterate http://common-lisp.net/project/iterate/

● ContextL http://common-lisp.net/project/closer/contextl.html

● chtml-matcher http://common-lisp.net/project/chtml-matcher/

● uri-template http://common-lisp.net/project/uri-template/

More Related Content

What's hot (20)

PDF
Virtual machine and javascript engine
Duoyi Wu
 
PDF
C c++-meetup-1nov2017-autofdo
Kim Phillips
 
PDF
Modern c++ Memory Management
Alan Uthoff
 
PDF
When RV Meets CEP (RV 2016 Tutorial)
Sylvain Hallé
 
PDF
Gaucheで本を作る
guest7a66b8
 
DOC
Macroprocessor
ksanthosh
 
PDF
Exploiting vectorization with ISPC
Roberto Agostino Vitillo
 
PDF
RxJS Evolved
trxcllnt
 
PDF
Powered by Python - PyCon Germany 2016
Steffen Wenz
 
PDF
Cluj.py Meetup: Extending Python in C
Steffen Wenz
 
PDF
Cluj Big Data Meetup - Big Data in Practice
Steffen Wenz
 
PDF
Javascript compilation execution
Fanis Prodromou
 
DOC
VLSI Sequential Circuits II
Gouthaman V
 
PDF
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
Sylvain Hallé
 
PDF
Clojure+ClojureScript Webapps
Falko Riemenschneider
 
PDF
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
PPTX
Scope and closures
Monu Chaudhary
 
PDF
Activity Recognition Through Complex Event Processing: First Findings
Sylvain Hallé
 
PDF
Compose Async with RxJS
Kyung Yeol Kim
 
PDF
Garbage Collection
Eelco Visser
 
Virtual machine and javascript engine
Duoyi Wu
 
C c++-meetup-1nov2017-autofdo
Kim Phillips
 
Modern c++ Memory Management
Alan Uthoff
 
When RV Meets CEP (RV 2016 Tutorial)
Sylvain Hallé
 
Gaucheで本を作る
guest7a66b8
 
Macroprocessor
ksanthosh
 
Exploiting vectorization with ISPC
Roberto Agostino Vitillo
 
RxJS Evolved
trxcllnt
 
Powered by Python - PyCon Germany 2016
Steffen Wenz
 
Cluj.py Meetup: Extending Python in C
Steffen Wenz
 
Cluj Big Data Meetup - Big Data in Practice
Steffen Wenz
 
Javascript compilation execution
Fanis Prodromou
 
VLSI Sequential Circuits II
Gouthaman V
 
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
Sylvain Hallé
 
Clojure+ClojureScript Webapps
Falko Riemenschneider
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
Scope and closures
Monu Chaudhary
 
Activity Recognition Through Complex Event Processing: First Findings
Sylvain Hallé
 
Compose Async with RxJS
Kyung Yeol Kim
 
Garbage Collection
Eelco Visser
 

Viewers also liked (19)

PDF
Visualizing user experience
Prasanna Revan
 
PDF
Refactor Yourself with Balalaika
dudarev
 
PDF
Donetsk Twitter
dudarev
 
PPT
Prodinzova
odinz.alena
 
PPT
Presentatie Xbiv5 1 0 Slide Share
SvenConvenso
 
PDF
Ololog
dudarev
 
PDF
Mobile applications with HTML and Javascript
dudarev
 
PDF
Functional Programming in Python
dudarev
 
PDF
Who are we?
dudarev
 
PPTX
Rat Pack
tcrollings
 
PPT
Presentatie Xbiv5 1 0 Slide Share
SvenConvenso
 
PPT
Bolzoni 360 Rotator Model RC
Brian_Garner
 
PPT
Carton Clamp Model KS-Z
Brian_Garner
 
PPT
360 Degree Rotating Paper Roll Clamps
Brian_Garner
 
PPT
Bolzoni Auramo Push Pulls 2010
Brian_Garner
 
KEY
About playdocja
yuichiro umezawa
 
PPT
Fork Presentation 01 2010
Brian_Garner
 
PPT
Operator Training Paper Roll Handling General
Brian_Garner
 
PPT
Forcematic-Clamp Pressure Control
Brian_Garner
 
Visualizing user experience
Prasanna Revan
 
Refactor Yourself with Balalaika
dudarev
 
Donetsk Twitter
dudarev
 
Prodinzova
odinz.alena
 
Presentatie Xbiv5 1 0 Slide Share
SvenConvenso
 
Ololog
dudarev
 
Mobile applications with HTML and Javascript
dudarev
 
Functional Programming in Python
dudarev
 
Who are we?
dudarev
 
Rat Pack
tcrollings
 
Presentatie Xbiv5 1 0 Slide Share
SvenConvenso
 
Bolzoni 360 Rotator Model RC
Brian_Garner
 
Carton Clamp Model KS-Z
Brian_Garner
 
360 Degree Rotating Paper Roll Clamps
Brian_Garner
 
Bolzoni Auramo Push Pulls 2010
Brian_Garner
 
About playdocja
yuichiro umezawa
 
Fork Presentation 01 2010
Brian_Garner
 
Operator Training Paper Roll Handling General
Brian_Garner
 
Forcematic-Clamp Pressure Control
Brian_Garner
 
Ad

Similar to CL metaprogramming (20)

PDF
Introduction To Lisp
kyleburton
 
PDF
The Magnificent Seven
Mike Fogus
 
PDF
ANSI C REFERENCE CARD
Tia Ricci
 
TXT
Procesos
PublioScipion
 
PPSX
Scala @ TomTom
Eric Bowman
 
PDF
Pune Clojure Course Outline
Baishampayan Ghose
 
PDF
Meta-objective Lisp @名古屋 Reject 会議
dico_leque
 
PDF
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
Functional Thursday
 
ODP
Clojure basics
Knoldus Inc.
 
PDF
Refactoring to Macros with Clojure
Dmitry Buzdin
 
PDF
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Zalando Technology
 
DOCX
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
Noppanon YourJust'one
 
ODP
Introduction to R
agnonchik
 
PPTX
Groovy
Zen Urban
 
ZIP
Lisp Macros in 20 Minutes (Featuring Clojure)
Phil Calçado
 
PPTX
โปรแกรมย่อยและฟังชันก์มาตรฐาน
knang
 
DOCX
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 
PDF
Programming Lisp Clojure - 2장 : 클로저 둘러보기
JangHyuk You
 
PDF
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
PDF
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Arvind Surve
 
Introduction To Lisp
kyleburton
 
The Magnificent Seven
Mike Fogus
 
ANSI C REFERENCE CARD
Tia Ricci
 
Procesos
PublioScipion
 
Scala @ TomTom
Eric Bowman
 
Pune Clojure Course Outline
Baishampayan Ghose
 
Meta-objective Lisp @名古屋 Reject 会議
dico_leque
 
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
Functional Thursday
 
Clojure basics
Knoldus Inc.
 
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Zalando Technology
 
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
Noppanon YourJust'one
 
Introduction to R
agnonchik
 
Groovy
Zen Urban
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Phil Calçado
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
knang
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
JangHyuk You
 
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Arvind Surve
 
Ad

Recently uploaded (20)

PDF
July Patch Tuesday
Ivanti
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
July Patch Tuesday
Ivanti
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 

CL metaprogramming

  • 1. Метапрограммирование в CL "Lisp isn't a language, it's a building material." - Alan Kay ● Макросы ● Макросы чтения ● Макросы компилятора ● ...
  • 2. Квазицитирование (defmacro nif (expr positive zero negative) (let ((var (gensym))) `(let ((,var ,expr)) (cond ((plusp ,var) ,positive) ((zerop ,var) ,zero) (t ,negative))))) (nif (- (* b b) (* 4 a c)) 2 1 0) (LET ((#:G624 (- (* B B) (* 4 A C)))) (COND ((PLUSP #:G624) 2) ((ZEROP #:G624) 1) (T 0)))
  • 3. Анафорические макросы (defmacro aif (condition then &optional else) `(let ((it ,condition)) (if it ,then ,else))) (aif (load-data)) (pprint it) (print "No data loaded.")) awhen, awhile, aand, alambda... (aand (load-data) (take-field it) (do-smth it))
  • 4. Декораторы (defmacro defun/decorated ((&rest decorator) name (&rest params) &body body) `(defun ,name (,@params) (,@decorator (lambda () ,@body) ,@params))) (defun decorator (x f &rest params) (format t "decorator ~A ~{~A ~}" x params) (funcall f)) (defun/decorated (decorator "smth") square (x) (* x x))
  • 5. Макросы пишут макросы: TCO (defun fact (n acc) (if (zerop n) acc (fact (- n 1) (* n acc)))) (defmacro defun/tco (name (&rest params) &body body) `(defun ,name (,@params) (macrolet ((,name (&rest args) `(progn (psetq ,@(mapcan (lambda (p v) (list p v)) ',params args)) (go :label)))) (tagbody :label (return-from ,name (progn ,@body)))))) (defun/tco fact/tco (n acc) (if (zerop n) acc (fact/tco (- n 1) (* n acc))))
  • 6. EDSL ● CLOS (Common Lisp Object System) ● ITERATE (iter (for i from 1) (for a in some-list) (collect (cons i a))) ● ContextL (AOP) ● Chtml-matcher (<tbody nil (tr nil (<a ((name ?post-num))) (tr nil) (tr nil (?post-body <div ((id "post_message_?"))))))
  • 7. Макросы чтения (set-dispatch-macro-character ## #$ #'(lambda (stream char arg) (parse-integer (coerce (loop for ch = (peek-char nil stream nil nil t) while (or (digit-char-p ch) (eql ch #_)) do (read-char stream t nil t) if (digit-char-p ch) collect ch) 'string)))) #$1_000_000
  • 8. Макросы чтения (let ((foo 1)) #Uhttp://www.example.com/widget/{foo}/parts) "http://www.example.com/widget/1/parts" (uri-template-bind (#Uhttp://www.example.com/{part}/{number}) "http://www.example.com/widget/1" (list part (parse-integer number) %uri-host)) ("widget" 1 "www.example.com")
  • 9. Макросы чтения (set-dispatch-macro-character ## #/ (lambda (stream char arg) (let ((pattern (coerce (loop for ch = (read-char stream t nil t) until (eql ch #/) collect ch) 'string))) `(lambda (&rest args) (apply #'cl-ppcre:scan ,pattern args))))) (#/[a-z]+/ str) ((lambda (&rest args) (apply #'cl-ppcre:scan "[a-z]+" args)) str) (cl-ppcre:scan "[a-z]+" str)
  • 10. Макросы компилятора (format stream control-string arg1...) (funcall (formatter control-string) stream arg1 ...) (lambda (stream &rest arguments) (apply #'format stream control-string arguments)) (formatter "Hello, ~A") (LAMBDA (STREAM #:FORMAT-ARG633) (WRITE-STRING "Hello, " STREAM) (PRINC #:FORMAT-ARG633 STREAM)) (formatter "~{~A~%~}") (LAMBDA (STREAM #:FORMAT-ARG636) (LET ((ARGS #:FORMAT-ARG636)) (LOOP (WHEN (NULL ARGS) (RETURN)) (PRINC (POP ARGS) STREAM) (TERPRI STREAM))))
  • 11. Макросы компилятора CL-PPCRE (define-compiler-macro scan (&whole form &environment env regex target-string &rest rest) (cond ((constantp regex env) `(scan (load-time-value (create-scanner ,regex)) ,target-string ,@rest)) (t form)))
  • 12. Ссылки ● Paul Graham «On Lisp» http://www.paulgraham.com/onlisp.html ● Doug Hoyte «LOL» http://letoverlambda.com/ ● CL-PPCRE http://weitz.de/cl-ppcre/ ● Iterate http://common-lisp.net/project/iterate/ ● ContextL http://common-lisp.net/project/closer/contextl.html ● chtml-matcher http://common-lisp.net/project/chtml-matcher/ ● uri-template http://common-lisp.net/project/uri-template/