SlideShare uma empresa Scribd logo
1 de 34
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*
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))))
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

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java Notes
Java Notes Java Notes
Java Notes
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Chapter 6 Intermediate Code Generation
Chapter 6   Intermediate Code GenerationChapter 6   Intermediate Code Generation
Chapter 6 Intermediate Code Generation
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Python Programming
Python Programming Python Programming
Python Programming
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
C++ oop
C++ oopC++ oop
C++ oop
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 

Semelhante a Lisp Macros in 20 Minutes (Featuring Clojure)

Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
dico_leque
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
Jan Kronquist
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 

Semelhante a Lisp Macros in 20 Minutes (Featuring Clojure) (20)

Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
Groovy
GroovyGroovy
Groovy
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Dynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web siteDynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web site
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
Perl basics for pentesters part 2
Perl basics for pentesters part 2Perl basics for pentesters part 2
Perl basics for pentesters part 2
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 

Mais de Phil Calçado

the afterparty: refactoring after 100x hypergrowth
the afterparty: refactoring after 100x hypergrowththe afterparty: refactoring after 100x hypergrowth
the afterparty: refactoring after 100x hypergrowth
Phil Calçado
 
don't try this at home: self-improvement as a senior leader
don't try this at home: self-improvement as a senior leaderdon't try this at home: self-improvement as a senior leader
don't try this at home: self-improvement as a senior leader
Phil Calçado
 
From microservices to serverless - Chicago CTO Summit 2019
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çado
 
The Not-So-Straightforward Road From Microservices to Serverless
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ç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 ...
Microservices vs. The First Law of Distributed Objects - GOTO Nights Chicago ...
Phil Calçado
 
An example of Future composition in a real app
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çado
 
Evolutionary Architecture at Work
Evolutionary  Architecture at WorkEvolutionary  Architecture at Work
Evolutionary Architecture at Work
Phil Calçado
 
Structuring apps in Scala
Structuring apps in ScalaStructuring apps in Scala
Structuring apps in Scala
Phil Calçado
 

Mais de Phil Calçado (20)

the afterparty: refactoring after 100x hypergrowth
the afterparty: refactoring after 100x hypergrowththe afterparty: refactoring after 100x hypergrowth
the afterparty: refactoring after 100x hypergrowth
 
don't try this at home: self-improvement as a senior leader
don't try this at home: self-improvement as a senior leaderdon't try this at home: self-improvement as a senior leader
don't try this at home: self-improvement as a senior leader
 
The Economics of Microservices (redux)
The Economics of Microservices (redux)The Economics of Microservices (redux)
The Economics of Microservices (redux)
 
From microservices to serverless - Chicago CTO Summit 2019
From microservices to serverless - Chicago CTO Summit 2019From microservices to serverless - Chicago CTO Summit 2019
From microservices to serverless - Chicago CTO Summit 2019
 
The Not-So-Straightforward Road From Microservices to Serverless
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
 
Ten Years of Failing Microservices
Ten Years of Failing MicroservicesTen Years of Failing Microservices
Ten Years of Failing Microservices
 
The Next Generation of Microservices
The Next Generation of MicroservicesThe Next Generation of Microservices
The Next Generation of Microservices
 
The Next Generation of Microservices — YOW 2017 Brisbane
The Next Generation of Microservices — YOW 2017 BrisbaneThe Next Generation of Microservices — YOW 2017 Brisbane
The Next Generation of Microservices — YOW 2017 Brisbane
 
The Economics of Microservices (2017 CraftConf)
The Economics of Microservices  (2017 CraftConf)The Economics of Microservices  (2017 CraftConf)
The Economics of Microservices (2017 CraftConf)
 
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 ...
Microservices vs. The First Law of Distributed Objects - GOTO Nights Chicago ...
 
Finagle @ SoundCloud
Finagle @ SoundCloudFinagle @ SoundCloud
Finagle @ SoundCloud
 
A Brief Talk On High-Performing Organisations
A Brief Talk On High-Performing OrganisationsA Brief Talk On High-Performing Organisations
A Brief Talk On High-Performing Organisations
 
Three Years of Microservices at SoundCloud - Distributed Matters Berlin 2015
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
 
Rhein-Main Scala Enthusiasts — Your microservice as a Function
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
 
ScalaItaly 2015 - Your Microservice as a Function
ScalaItaly 2015 - Your Microservice as a FunctionScalaItaly 2015 - Your Microservice as a Function
ScalaItaly 2015 - Your Microservice as a Function
 
Finagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloudFinagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloud
 
An example of Future composition in a real app
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
 
APIs: The Problems with Eating your Own Dog Food
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
 
Evolutionary Architecture at Work
Evolutionary  Architecture at WorkEvolutionary  Architecture at Work
Evolutionary Architecture at Work
 
Structuring apps in Scala
Structuring apps in ScalaStructuring apps in Scala
Structuring apps in Scala
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

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*
  • 14.
  • 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))))
  • 21.
  • 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)))

Notas do Editor