Lisp Macros in 20 Minutes (Featuring Clojure)

Phil Calçado
Lisp Macros
                   in 20 minutes
                           (featuring ‘clojure)

                                               phillip calçado
                                            http://fragmental.tw
                                          http://thoughtworks.com


--:--   *LISP Macros in 20 minutes*   http://fragmental.tw (Presentation)--------------------------------------------------------
Clojure
Clojure


•homoiconic
•fairly functional
•runtime polymorphism
•jvm language
•software transactional memory
•agent-based asynchronous concurrency
Clojure


•homoiconic
•fairly functional
•runtime polymorphism
•jvm language
•software transactional memory
•agent-based asynchronous concurrency
Clojure


•homoiconic
•fairly functional
•runtime polymorphism
•jvm language
    Code is Data
•software transactional memory
•agent-based asynchronous concurrency

    Data is Code
Example:
LINQ Envy
C#


    string[] names = { quot;Burkequot;, quot;Connorquot;, quot;Frankquot;,
                       quot;Everettquot;, quot;Albertquot;, quot;Georgequot;,
                       quot;Harrisquot;, quot;Davidquot; };

    IEnumerable<string> query = from n in names
                               where n.Length == 5
                               orderby n
                               select n.ToUpper();

    foreach (string item in query)
      Console.WriteLine(item);
}
Java - Quaere


String[] names={quot;Burkequot;, quot;Connorquot;, quot;Frankquot;,
                       quot;Everettquot;, quot;Albertquot;, quot;Georgequot;,
                       quot;Harrisquot;, quot;Davidquot;};
Iterable<String> query=
        from(quot;nquot;).in(names).
        where(eq(quot;n.length()quot;,5).
        select(quot;n.toUpperCase()quot;);

for (String n: query) {
    System.out.println(n);
}
Ruby - Quick Hack


names = [quot;Burkequot;, quot;Connorquot;, quot;Frankquot;,
         quot;Everettquot;, quot;Albertquot;, quot;Georgequot;,
         quot;Harrisquot;, quot;Davidquot;]

query = from :n => names do
  where n.length => 5
  orderby n
  select n.upcase
end

query.each{|e| puts e   }
Clojure


(def names '(quot;Burkequot;, quot;Connorquot;, quot;Frankquot;,
                       quot;Everettquot;, quot;Albertquot;,
                       quot;Georgequot;, quot;Harrisquot;,
                       quot;Davidquot;))

(def query
      (from n in names
      where (= (. n length) 5)
      orderby n
      select (. n toUpperCase)))

(doseq [n query] (println n))
Ruby Hack - Implementation
class Parameter                                            def from(binding, &spec)
  def method_missing(method, *args)                         var = binding.keys.first
    method                                                  list = binding.values.last
  end                                                       query = Query.new var
end                                                         query.instance_eval &spec
                                                            list.select do |a|
class Query                                                   a.send(query.condition[:method]) ==
  attr_reader :condition, :criteria, :action              query.condition[:value]
                                                            end.sort do |a,b|
  def initialize(var)                                         if(query.criteria)
    singleton_class.send(:define_method, var)                   a.send(query.criteria) <=> b.send(query.criteria)
{ Parameter.new }                                             else
  end                                                           a <=> b
                                                              end
  def singleton_class; class << self; self; end; end        end.map do |a|
                                                              a.send(query.action)
  def where(cond)                                           end
    @condition = {:method => cond.keys.first, :value =>   end
cond.values.last}
  end

  def orderby(criteria)
    @criteria = criteria unless criteria.kind_of?
Parameter
  end

  def select(action)
    @action = action
  end
end
      a <=> b
    end
  end.map do |a|
    a.send(query.action)
  end
end
Clojure - Implementation




(defmacro from [var _ coll _ condition _ ordering _ desired-map]
  `(map (fn [~var] ~desired-map) (sort-by (fn[~var] ~ordering)
	      (filter (fn[~var] ~condition) ~coll))))
Code is Data
                     Data is Code
 “         InfoQ: [...] many modern programming languages like Ruby are claiming big
           influences from Lisp Have you seen those languages or do you have any ideas
           about the current state of programming languages?

           McCarthy: [...] I don't know enough for example about Ruby to know in what way
           it's related to Lisp. Does it use, for example, list structures as data?

           InfoQ: No.

           McCarthy: So if you want to compute with sums and products, you have to parse
           every time?

           InfoQ: Yes.

           McCarthy: So, in that respect Ruby still isn't up to where Lisp was in 1960.


Adapted From: http://www.infoq.com/interviews/mccarthy-elephant-2000*
Lisp Macros in 20 Minutes (Featuring Clojure)
Everything is
  a (List)
(1 2 3 4 5)


   (+ 1 2)


(+ (- 3 2) 10)
List


{
(1 2 3 4 5)


  Number
List


           {
       (+ 1 2)


Function     Number
List

     {
     (+ (- 3 2) 10)

       {   List
Function          Number
{
           (defn- run-variant[variant]
             (let [result
               (wrap-and-run


List
                 (:impl variant) (:args variant))]
                   (struct-map variant-result
                     :args (:args variant)
                     :result (first result)
                     :exception (second result))))
Lisp Macros in 20 Minutes (Featuring Clojure)
Code is Data
Data is Code
Example:
Implementing
     If
(defn they-are-the-same []
  (println quot;They are the same!quot;))

(defn they-are-different []
  (println quot;They are different!quot;))

(my-if (= 2 2)
       (they-are-the-same)
       (they-are-different))
First Try: Function



(defn my-if [condition succ fail]
  (cond
   condition succ
   :else fail))



user>
;;;; (my-if (= 2 2)         (they-are-the-
same)         (they-are ...
They are the same!
They are different!
Second Try: Macro



(defmacro my-if [condition succ fail]
  (cond
   condition succ
   :else fail))



user>
;;;; (my-if (= 2 2)         (they-are-the-
same)         (they-are ...
They are the same!
Why? Dump Function Arguments



(defn my-if [condition succ fail]
  (println quot;Parameters are: quot; condition
succ fail))



user>
user>
;;;; (my-if (= 2 2)         (they-are-the-
same)         (they-are ...
They are the same!
They are different!
Parameters are: true nil nil
Why? Dump Macro Arguments



(defmacro my-if [condition succ fail]
  (println quot;Parameters are: quot; condition
succ fail))



user>
user>
;;;; (My-if (= 2 2)         (they-are-the-
same)         (they-are ...
Parameters are: (= 2 2) (they-are-the-
same) (they-are-different)
Macro Expansion



(println (macroexpand-1 '(my-if (= 2 2)
		         (they-are-the-same)
		         (they-are-different)))




user>
user>
(they-are-the-same)
(my-if (= 2 2)
       (they-are-the-same)
       (they-are-different))




(defmacro my-if [condition succ fail]
  (cond
   condition succ
   :else fail))




(they-are-the-same)
Revisiting
  LINQ
Clojure - Implementation




(defmacro from [var _ coll _ condition _ ordering _ desired-map]
  `(map (fn [~var] ~desired-map) (sort-by (fn[~var] ~ordering)
	      (filter (fn[~var] ~condition) ~coll))))
(def query
      (from n in names
      where (= (. n length) 5)
      orderby n
      select (. n toUpperCase)))



(defmacro from [var _ coll _ condition _ ordering _
desired-map]
  `(map (fn [~var] ~desired-map) (sort-by (fn[~var]
~ordering)
	      (filter (fn[~var] ~condition) ~coll))))




(map (fn [n] (. n toUpperCase)) (sort-by (fn [n] n)
(filter (fn [n] (= (. n length) 5)) names)))
More?
http://www.pragprog.com/titles/shcloj/
programming-clojure

http://www.lisperati.com/casting.html

http://groups.google.com/group/clojure

http://www.gigamonkeys.com/book/

http://mitpress.mit.edu/sicp/

http://github.com/pcalcado/fato/tree/master
1 of 34

Recommended

(ThoughtWorks Away Day 2009) one or two things you may not know about typesys... by
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...Phil Calçado
3.2K views47 slides
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado by
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoJustjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip CalçadoPaulo Silveira
1.3K views53 slides
Type Driven Development with TypeScript by
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
388 views84 slides
Ast transformations by
Ast transformationsAst transformations
Ast transformationsHamletDRC
792 views75 slides
TypeScript Introduction by
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
7.4K views53 slides
AST Transformations at JFokus by
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
945 views101 slides

More Related Content

What's hot

Hacking Go Compiler Internals / GoCon 2014 Autumn by
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnMoriyoshi Koizumi
7.6K views19 slides
JavaScript 2016 for C# Developers by
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
563 views50 slides
Building native Android applications with Mirah and Pindah by
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
6.3K views40 slides
JavaScript ES6 by
JavaScript ES6JavaScript ES6
JavaScript ES6Leo Hernandez
1.4K views23 slides
Building fast interpreters in Rust by
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
4.7K views80 slides
Fun with Lambdas: C++14 Style (part 2) by
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Sumant Tambe
51.6K views30 slides

What's hot(20)

Hacking Go Compiler Internals / GoCon 2014 Autumn by Moriyoshi Koizumi
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi7.6K views
JavaScript 2016 for C# Developers by Rick Beerendonk
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
Rick Beerendonk563 views
Building native Android applications with Mirah and Pindah by Nick Plante
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
Nick Plante6.3K views
Building fast interpreters in Rust by Ingvar Stepanyan
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
Ingvar Stepanyan4.7K views
Fun with Lambdas: C++14 Style (part 2) by Sumant Tambe
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe51.6K views
EcmaScript 6 by Manoj Kumar
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar1.7K views
2018 cosup-delete unused python code safely - english by Jen Yee Hong
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
Jen Yee Hong1.7K views
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014 by Susan Potter
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Susan Potter2.9K views
JavaScript - new features in ECMAScript 6 by Solution4Future
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future21.8K views
Functional Algebra: Monoids Applied by Susan Potter
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
Susan Potter4.1K views
"Немного о функциональном программирование в JavaScript" Алексей Коваленко by Fwdays
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays4.5K views
ES6 PPT FOR 2016 by Manoj Kumar
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar2.8K views
ClojureScript: The Good Parts by Kent Ohashi
ClojureScript: The Good PartsClojureScript: The Good Parts
ClojureScript: The Good Parts
Kent Ohashi3K views
ConFess Vienna 2015 - Metaprogramming with Groovy by Iván López Martín
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with Groovy

Similar to Lisp Macros in 20 Minutes (Featuring Clojure)

Clojure: Practical functional approach on JVM by
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMsunng87
1.7K views48 slides
Groovy by
GroovyGroovy
GroovyZen Urban
1.1K views35 slides
Meta-objective Lisp @名古屋 Reject 会議 by
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議dico_leque
940 views20 slides
Pune Clojure Course Outline by
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course OutlineBaishampayan Ghose
686 views32 slides
ClojureScript loves React, DomCode May 26 2015 by
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
411 views52 slides
(map Clojure everyday-tasks) by
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
1.6K views90 slides

Similar to Lisp Macros in 20 Minutes (Featuring Clojure)(20)

Clojure: Practical functional approach on JVM by sunng87
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
sunng871.7K views
Groovy by Zen Urban
GroovyGroovy
Groovy
Zen Urban1.1K views
Meta-objective Lisp @名古屋 Reject 会議 by dico_leque
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
dico_leque940 views
ClojureScript loves React, DomCode May 26 2015 by Michiel Borkent
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent411 views
Scala + WattzOn, sitting in a tree.... by Raffi Krikorian
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
Raffi Krikorian1.6K views
Introduction to Scalding and Monoids by Hugo Gävert
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert7.6K views
Hacking with ruby2ruby by Marc Chung
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
Marc Chung1.4K views
Clojure for Java developers - Stockholm by Jan Kronquist
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
Jan Kronquist1.7K views
Introduction To Lisp by kyleburton
Introduction To LispIntroduction To Lisp
Introduction To Lisp
kyleburton6.6K views
Ruby on Rails Intro by zhang tao
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
zhang tao294 views
JavaScript Growing Up by David Padbury
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury14.1K views
The Swift Compiler and Standard Library by Santosh Rajan
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan10.4K views
Dynamic Tracing of your AMP web site by Sriram Natarajan
Dynamic Tracing of your AMP web siteDynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web site
Sriram Natarajan1.3K views
Unit testing JavaScript using Mocha and Node by Josh Mock
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock11.2K views

More from Phil Calçado

The Economics of Microservices (redux) by
The Economics of Microservices (redux)The Economics of Microservices (redux)
The Economics of Microservices (redux)Phil Calçado
760 views59 slides
From microservices to serverless - Chicago CTO Summit 2019 by
From microservices to serverless - Chicago CTO Summit 2019From microservices to serverless - Chicago CTO Summit 2019
From microservices to serverless - Chicago CTO Summit 2019Phil Calçado
1.1K views28 slides
The Not-So-Straightforward Road From Microservices to Serverless by
The Not-So-Straightforward Road From Microservices to ServerlessThe Not-So-Straightforward Road From Microservices to Serverless
The Not-So-Straightforward Road From Microservices to ServerlessPhil Calçado
1.1K views47 slides
Ten Years of Failing Microservices by
Ten Years of Failing MicroservicesTen Years of Failing Microservices
Ten Years of Failing MicroservicesPhil Calçado
1.8K views48 slides
The Next Generation of Microservices by
The Next Generation of MicroservicesThe Next Generation of Microservices
The Next Generation of MicroservicesPhil Calçado
1.3K views52 slides
The Next Generation of Microservices — YOW 2017 Brisbane by
The Next Generation of Microservices — YOW 2017 BrisbaneThe Next Generation of Microservices — YOW 2017 Brisbane
The Next Generation of Microservices — YOW 2017 BrisbanePhil Calçado
886 views52 slides

More from Phil Calçado(20)

The Economics of Microservices (redux) by Phil Calçado
The Economics of Microservices (redux)The Economics of Microservices (redux)
The Economics of Microservices (redux)
Phil Calçado760 views
From microservices to serverless - Chicago CTO Summit 2019 by Phil Calçado
From microservices to serverless - Chicago CTO Summit 2019From microservices to serverless - Chicago CTO Summit 2019
From microservices to serverless - Chicago CTO Summit 2019
Phil Calçado1.1K views
The Not-So-Straightforward Road From Microservices to Serverless by Phil Calçado
The Not-So-Straightforward Road From Microservices to ServerlessThe Not-So-Straightforward Road From Microservices to Serverless
The Not-So-Straightforward Road From Microservices to Serverless
Phil Calçado1.1K views
Ten Years of Failing Microservices by Phil Calçado
Ten Years of Failing MicroservicesTen Years of Failing Microservices
Ten Years of Failing Microservices
Phil Calçado1.8K views
The Next Generation of Microservices by Phil Calçado
The Next Generation of MicroservicesThe Next Generation of Microservices
The Next Generation of Microservices
Phil Calçado1.3K views
The Next Generation of Microservices — YOW 2017 Brisbane by Phil Calçado
The Next Generation of Microservices — YOW 2017 BrisbaneThe Next Generation of Microservices — YOW 2017 Brisbane
The Next Generation of Microservices — YOW 2017 Brisbane
Phil Calçado886 views
The Economics of Microservices (2017 CraftConf) by Phil Calçado
The Economics of Microservices  (2017 CraftConf)The Economics of Microservices  (2017 CraftConf)
The Economics of Microservices (2017 CraftConf)
Phil Calçado3.8K views
Microservices vs. The First Law of Distributed Objects - GOTO Nights Chicago ... by Phil Calçado
Microservices vs. The First Law of Distributed Objects - GOTO Nights Chicago ...Microservices vs. The First Law of Distributed Objects - GOTO Nights Chicago ...
Microservices vs. The First Law of Distributed Objects - GOTO Nights Chicago ...
Phil Calçado1.4K views
A Brief Talk On High-Performing Organisations by Phil Calçado
A Brief Talk On High-Performing OrganisationsA Brief Talk On High-Performing Organisations
A Brief Talk On High-Performing Organisations
Phil Calçado2.9K views
Three Years of Microservices at SoundCloud - Distributed Matters Berlin 2015 by Phil Calçado
Three Years of Microservices at SoundCloud - Distributed Matters Berlin 2015Three Years of Microservices at SoundCloud - Distributed Matters Berlin 2015
Three Years of Microservices at SoundCloud - Distributed Matters Berlin 2015
Phil Calçado3.1K views
Rhein-Main Scala Enthusiasts — Your microservice as a Function by Phil Calçado
Rhein-Main Scala Enthusiasts — Your microservice as a FunctionRhein-Main Scala Enthusiasts — Your microservice as a Function
Rhein-Main Scala Enthusiasts — Your microservice as a Function
Phil Calçado3.5K views
ScalaItaly 2015 - Your Microservice as a Function by Phil Calçado
ScalaItaly 2015 - Your Microservice as a FunctionScalaItaly 2015 - Your Microservice as a Function
ScalaItaly 2015 - Your Microservice as a Function
Phil Calçado4.4K views
Finagle-Based Microservices at SoundCloud by Phil Calçado
Finagle-Based Microservices at SoundCloudFinagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloud
Phil Calçado5.5K views
An example of Future composition in a real app by Phil Calçado
An example of Future composition in a real appAn example of Future composition in a real app
An example of Future composition in a real app
Phil Calçado3.8K views
APIs: The Problems with Eating your Own Dog Food by Phil Calçado
APIs: The Problems with Eating your Own Dog FoodAPIs: The Problems with Eating your Own Dog Food
APIs: The Problems with Eating your Own Dog Food
Phil Calçado5K views
Evolutionary Architecture at Work by Phil Calçado
Evolutionary  Architecture at WorkEvolutionary  Architecture at Work
Evolutionary Architecture at Work
Phil Calçado3.8K views
Structuring apps in Scala by Phil Calçado
Structuring apps in ScalaStructuring apps in Scala
Structuring apps in Scala
Phil Calçado1.6K views
From a monolithic Ruby on Rails app to the JVM by Phil Calçado
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVM
Phil Calçado59.9K views
Applying Evolutionary Architecture on a Popular API by Phil Calçado
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular API
Phil Calçado4.1K views

Recently uploaded

LLMs in Production: Tooling, Process, and Team Structure by
LLMs in Production: Tooling, Process, and Team StructureLLMs in Production: Tooling, Process, and Team Structure
LLMs in Production: Tooling, Process, and Team StructureAggregage
57 views77 slides
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...ShapeBlue
183 views18 slides
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueShapeBlue
207 views54 slides
Future of Indian ConsumerTech by
Future of Indian ConsumerTechFuture of Indian ConsumerTech
Future of Indian ConsumerTechKapil Khandelwal (KK)
36 views68 slides
Business Analyst Series 2023 - Week 4 Session 8 by
Business Analyst Series 2023 -  Week 4 Session 8Business Analyst Series 2023 -  Week 4 Session 8
Business Analyst Series 2023 - Week 4 Session 8DianaGray10
145 views13 slides
State of the Union - Rohit Yadav - Apache CloudStack by
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStackShapeBlue
303 views53 slides

Recently uploaded(20)

LLMs in Production: Tooling, Process, and Team Structure by Aggregage
LLMs in Production: Tooling, Process, and Team StructureLLMs in Production: Tooling, Process, and Team Structure
LLMs in Production: Tooling, Process, and Team Structure
Aggregage57 views
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue183 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue207 views
Business Analyst Series 2023 - Week 4 Session 8 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 8Business Analyst Series 2023 -  Week 4 Session 8
Business Analyst Series 2023 - Week 4 Session 8
DianaGray10145 views
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue303 views
Future of AR - Facebook Presentation by Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty65 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10146 views
The Power of Heat Decarbonisation Plans in the Built Environment by IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE84 views
NTGapps NTG LowCode Platform by Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu437 views
"Package management in monorepos", Zoltan Kochan by Fwdays
"Package management in monorepos", Zoltan Kochan"Package management in monorepos", Zoltan Kochan
"Package management in monorepos", Zoltan Kochan
Fwdays34 views
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... by ShapeBlue
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
ShapeBlue108 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue141 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue224 views
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue137 views

Lisp Macros in 20 Minutes (Featuring Clojure)

  • 1. Lisp Macros in 20 minutes (featuring ‘clojure) phillip calçado http://fragmental.tw http://thoughtworks.com --:-- *LISP Macros in 20 minutes* http://fragmental.tw (Presentation)--------------------------------------------------------
  • 3. Clojure •homoiconic •fairly functional •runtime polymorphism •jvm language •software transactional memory •agent-based asynchronous concurrency
  • 4. Clojure •homoiconic •fairly functional •runtime polymorphism •jvm language •software transactional memory •agent-based asynchronous concurrency
  • 5. Clojure •homoiconic •fairly functional •runtime polymorphism •jvm language Code is Data •software transactional memory •agent-based asynchronous concurrency Data is Code
  • 7. C# string[] names = { quot;Burkequot;, quot;Connorquot;, quot;Frankquot;, quot;Everettquot;, quot;Albertquot;, quot;Georgequot;, quot;Harrisquot;, quot;Davidquot; }; IEnumerable<string> query = from n in names where n.Length == 5 orderby n select n.ToUpper(); foreach (string item in query) Console.WriteLine(item); }
  • 8. Java - Quaere String[] names={quot;Burkequot;, quot;Connorquot;, quot;Frankquot;, quot;Everettquot;, quot;Albertquot;, quot;Georgequot;, quot;Harrisquot;, quot;Davidquot;}; Iterable<String> query= from(quot;nquot;).in(names). where(eq(quot;n.length()quot;,5). select(quot;n.toUpperCase()quot;); for (String n: query) { System.out.println(n); }
  • 9. Ruby - Quick Hack names = [quot;Burkequot;, quot;Connorquot;, quot;Frankquot;, quot;Everettquot;, quot;Albertquot;, quot;Georgequot;, quot;Harrisquot;, quot;Davidquot;] query = from :n => names do where n.length => 5 orderby n select n.upcase end query.each{|e| puts e }
  • 10. Clojure (def names '(quot;Burkequot;, quot;Connorquot;, quot;Frankquot;, quot;Everettquot;, quot;Albertquot;, quot;Georgequot;, quot;Harrisquot;, quot;Davidquot;)) (def query (from n in names where (= (. n length) 5) orderby n select (. n toUpperCase))) (doseq [n query] (println n))
  • 11. Ruby Hack - Implementation class Parameter def from(binding, &spec) def method_missing(method, *args) var = binding.keys.first method list = binding.values.last end query = Query.new var end query.instance_eval &spec list.select do |a| class Query a.send(query.condition[:method]) == attr_reader :condition, :criteria, :action query.condition[:value] end.sort do |a,b| def initialize(var) if(query.criteria) singleton_class.send(:define_method, var) a.send(query.criteria) <=> b.send(query.criteria) { Parameter.new } else end a <=> b end def singleton_class; class << self; self; end; end end.map do |a| a.send(query.action) def where(cond) end @condition = {:method => cond.keys.first, :value => end cond.values.last} end def orderby(criteria) @criteria = criteria unless criteria.kind_of? Parameter end def select(action) @action = action end end a <=> b end end.map do |a| a.send(query.action) end end
  • 12. Clojure - Implementation (defmacro from [var _ coll _ condition _ ordering _ desired-map] `(map (fn [~var] ~desired-map) (sort-by (fn[~var] ~ordering) (filter (fn[~var] ~condition) ~coll))))
  • 13. Code is Data Data is Code “ InfoQ: [...] many modern programming languages like Ruby are claiming big influences from Lisp Have you seen those languages or do you have any ideas about the current state of programming languages? McCarthy: [...] I don't know enough for example about Ruby to know in what way it's related to Lisp. Does it use, for example, list structures as data? InfoQ: No. McCarthy: So if you want to compute with sums and products, you have to parse every time? InfoQ: Yes. McCarthy: So, in that respect Ruby still isn't up to where Lisp was in 1960. Adapted From: http://www.infoq.com/interviews/mccarthy-elephant-2000*
  • 15. Everything is a (List)
  • 16. (1 2 3 4 5) (+ 1 2) (+ (- 3 2) 10)
  • 17. List { (1 2 3 4 5) Number
  • 18. List { (+ 1 2) Function Number
  • 19. List { (+ (- 3 2) 10) { List Function Number
  • 20. { (defn- run-variant[variant] (let [result (wrap-and-run List (:impl variant) (:args variant))] (struct-map variant-result :args (:args variant) :result (first result) :exception (second result))))
  • 22. Code is Data Data is Code
  • 24. (defn they-are-the-same [] (println quot;They are the same!quot;)) (defn they-are-different [] (println quot;They are different!quot;)) (my-if (= 2 2) (they-are-the-same) (they-are-different))
  • 25. First Try: Function (defn my-if [condition succ fail] (cond condition succ :else fail)) user> ;;;; (my-if (= 2 2) (they-are-the- same) (they-are ... They are the same! They are different!
  • 26. Second Try: Macro (defmacro my-if [condition succ fail] (cond condition succ :else fail)) user> ;;;; (my-if (= 2 2) (they-are-the- same) (they-are ... They are the same!
  • 27. Why? Dump Function Arguments (defn my-if [condition succ fail] (println quot;Parameters are: quot; condition succ fail)) user> user> ;;;; (my-if (= 2 2) (they-are-the- same) (they-are ... They are the same! They are different! Parameters are: true nil nil
  • 28. Why? Dump Macro Arguments (defmacro my-if [condition succ fail] (println quot;Parameters are: quot; condition succ fail)) user> user> ;;;; (My-if (= 2 2) (they-are-the- same) (they-are ... Parameters are: (= 2 2) (they-are-the- same) (they-are-different)
  • 29. Macro Expansion (println (macroexpand-1 '(my-if (= 2 2) (they-are-the-same) (they-are-different))) user> user> (they-are-the-same)
  • 30. (my-if (= 2 2) (they-are-the-same) (they-are-different)) (defmacro my-if [condition succ fail] (cond condition succ :else fail)) (they-are-the-same)
  • 32. Clojure - Implementation (defmacro from [var _ coll _ condition _ ordering _ desired-map] `(map (fn [~var] ~desired-map) (sort-by (fn[~var] ~ordering) (filter (fn[~var] ~condition) ~coll))))
  • 33. (def query (from n in names where (= (. n length) 5) orderby n select (. n toUpperCase))) (defmacro from [var _ coll _ condition _ ordering _ desired-map] `(map (fn [~var] ~desired-map) (sort-by (fn[~var] ~ordering) (filter (fn[~var] ~condition) ~coll)))) (map (fn [n] (. n toUpperCase)) (sort-by (fn [n] n) (filter (fn [n] (= (. n length) 5)) names)))

Editor's Notes