SlideShare a Scribd company logo
Learn a language: Clojure
by Tijs van der Storm



Preliminaries
Install Eclipse, if you haven’t already. To get a “main-stream” IDE for Clojure, install the
CounterClockwise plugin for Eclipse. I use it with Eclipse Indigo, but I have no idea whether
other versions will work too.

The webpage for the plugin can be found here:
http://code.google.com/p/counterclockwise/. Use the Eclipse help menu to install extra
software, add the update site: http://ccw.cgrand.net/updatesite/.

Select the Clojure plugin. Next, accept, next, finish, restart Eclipse. Then File->New… select
Clojure project. Finish. To create a file, right-click on the project, select New->Other-
>Clojure namespace. To load/start a REPL (Read-Eval-Print-Loop) for the file, right-click the
editor, and select load into REPL. Your functions are now accessible in the REPL.

Some notes on the IDE:

       Command history is accessed through Ctrl-up and -down.
       In an editor, check the context menu for shortcuts to (re)load the current file.


Clojure resources

       Main site: http://www.clojure.org
       Quickref of clojure.core: http://clojuredocs.org/quickref/Clojure%20Core
       Index of clojure.core: http://clojuredocs.org/clojure_core




Exercises
Warming up
Type the following expression in the REPL.


   (print "Hello world!")
   (+ 1 2)
   (+ 1 2 3 4)
   *
   (map (fn [x] (+ x 2)) [1 2 3 4])
   (def f (fn [x] (+ x 2)))
   (defn g [x] (+ x 2))
   (map f [1 2 3 4]))
   (vec (map f [1 2 3 4])))
(vec (map f [1 2 3 4])))
   (reduce * [1 2 3 4])
   (if (> 2 1) 'yes 'no)



Quoting


   '()
   '4
   '(+ 3 4)
   '[Hello world!]
   (quote (+ 3 x))
   (list '+ 3 x)
   `(list '+ 3 x)
   (let [x 3] `(+ 3 ~x))
   (let [x '(4 5 6)] `(+ 3 ~@x))
   (let [x '(4 5 6)] (concat (list '+ 3) x))




Functional programming

    1. Write the factorial function.
    2. Implement the Fizz Buzz Test (see C2 http://c2.com/cgi/wiki?FizzBuzzTest). Tip: use
        doseq and range .
    3. Write the power function using recursion.
    4. Write the power function using squaring (see Wikipedia
       http://en.wikipedia.org/wiki/Exponentiation_by_squaring)
    5. Write the power function using reduce and repeat .


Macro programming
In Clojure, a macro is defined using defmacro :


  (defmacro m [a1 … an] body)



Here, m is the name of macro, a1 … an are the formal parameters and body is the body
of the macro. Macros are functions that return code. How the result is created does not
matter, but it is typical to use the quasiquote (backtick, `), unquote ( ~ ) and unquote splicing
( ~@ ). Note that when a macro is invoked (m e1 … en) , the argument expressions e1 …
en are not evaluated. In other words, the formal parameters a1 … an of m are bound to
the code trees of e1 … en . For instance, when calling (m (+ 1 2)) , a1 is bound to '(+
1 2) and not to 3 .

Tips for debugging macros:

       Use macroexpand and macroexpand-1 with a quoted macro invocation as
       argument to inspect what a top-level macro expands to.
To see complete expansion of a macro, first issue


             (use 'clojure.walk)



        at the REPL prompt, then you can use macroexpand-all .


Assert statement
Write a macro that implements an assert statement, as found in Java. The macro should be
called as follows:


  (assert* cond "some message")



The result of assert* should be nil). If the condition cond fails (i.e., returns false or
nil ) an exception should be thrown with a message containing the literal expression cond
and the label string.

Use throw to throw an exception, which can be created as follows (Exception. "some
message") . Use the str function to concatenate strings. NB: the failing expression should
be in the message. Tip: unquotes ( ~ ) can be in quotes ( ' )…

Quiz

Does assert* have to be a macro? If so why? If not, how would you implement it?

Aside

Practical Common Lisp devotes a chapter to writing a simple unit-test framework using
macros:

        http://www.gigamonkeys.com/book/practical-building-a-unit-test-framework.html


Let
The let construct to introduce local variables is a built-in special form in Clojure. However,
it is well-known that let can be implemented as a macro: an invocation of let expands
to a function application. Write such a macro. Your version of let ( let* ) should expand as
follows:


  (let* [var exp] body) => ((fn [var] body) exp)



To simplify the exercise, you may assume that let only binds a single variable. If this is too
simple, implement another version that supports multiple bindings.

Times
Times
Write a macro times that takes an expression e and a number n and expands to a do
form that just executes the expression n times. E.g.:


  (times 5 'hello) => (do 'hello 'hello 'hello 'hello 'hello)



Tip: use the splicing unquote ~@ in combination with the core function repeat . Note that
 repeat generates an (lazily) infinite sequence, you have to provide the number of
repetitions.

Special power
Partial evaluation is a program optimization technique that can be applied if certain
arguments to a function are statically known. A traditional example is the power function.
Often, the exponent argument ( n in (power x n) ) is statically known. Can we specialize
the power function for a fixed n ? Partial evaluation in general is not for the faint of heart,
but using macros we can do this specifically for power.

The goal is to write a macro that generates the code for a power function that is specialized
for some n . Let’s call it gen-power . Now, if (gen-power 3) returns a function f , then it
should hold that (= (f x) (power x 3)) for all x .

Here’s an example of what the invocation (gen-power 3) could expand to:


   (fn* ([x]
      (clojure.core/* x
      (clojure.core/* x
      (clojure.core/* x 1)))))



NB: fn* is an internal form Clojure to represent functions. Note that the * function has
been qualified with the namespace it is defined in. In the macro you can just use the normal
fn and * to generate code.


Tips
Split the solution in two parts:

    1. The top-level macro creates the function and calls a sub-function (gen-body 'x
       n) , where x represents the name of the parameter of the created function, and
       where n is the exponent.
    2. The gen-body function recursively creates an expression to multiply x n times.


Quiz

Argue why the specialized power functions produced by gen-power would/should be
faster than the general power function.
Computing derivatives
Check out this page to refresh your derivative chops:

       http://en.wikipedia.org/wiki/Derivative

In this exercise, the goal is to compute the derivative of restricted, but otherwise ordinary
Clojure functions. The restrictions are:

       Functions take only 1 argument.
       The body of the function can only use * , + , the formal parameter of the function,
       and constant numbers.
       You may assume both * and + only have two arguments (although Clojure supports
       an arbitrary number).

Basically, such functions describe simple polynomials. An example is the following:


  (fn [x] (+ (* 3 (* x x)) (+ (* 2 x) 1))))



The derivative of this function is:


  (fn [x] (+ (* 6 x)) 2))



The exercise is to write a macro that returns and expression that computes this function.
NB: this does not mean that it is syntactically the same as the derivative shown above; it
should however give the same answers for the same inputs.

The macro is invoked as follows:


  (deriv (fn [x] (+ (* 3 (* x x)) (+ (* 2 x) 1)))))




Tips
Split your solution in two parts:

    1. The top-level macro that analyzes the fn argument to obtain the name of the
       parameter and the body expression, passes it to 2), and upon return constructs a
       new fn with the same parameter.
    2. The helper function diff that receives and expression e and a variable name v
       which computes the derivative expression.

Some useful functions:

        (number? x) : returns true if x is a number.
        (symbol? x) : returns true if x is a symbol.
(first x) , (second x) : return the first resp. second elements of a collection
(vector or list) x .
 (nth x n) : return the n -th element of a collection x .
 (cond c1 e1 … cn en :else e) : cascading conditional; finds the first ci that
evaluates to true and evaluates ei . If no ci is found, evaluates e .

More Related Content

What's hot

Clojure basics
Clojure basicsClojure basics
Clojure basics
Knoldus Inc.
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
AravindSankaran
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
Programming Homework Help
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
David Atchley
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
Syed Hassan Kazmi
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame work
Rahul Kolluri
 
Java lab 2
Java lab 2Java lab 2
Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 

What's hot (20)

Clojure basics
Clojure basicsClojure basics
Clojure basics
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Class method
Class methodClass method
Class method
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame work
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Link list
Link listLink list
Link list
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 

Similar to Learn a language : LISP

Lecture 3
Lecture 3Lecture 3
Lecture 3
Muhammad Fayyaz
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
 
Matlab functions
Matlab functionsMatlab functions
Matlab functions
pramodkumar1804
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
aboma2hawi
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
e-Legion
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
Infinity Tech Solutions
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
C basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kellaC basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kella
Manoj Kumar kothagulla
 
Matlab integration
Matlab integrationMatlab integration
Matlab integration
pramodkumar1804
 
React native
React nativeReact native
Programming with effects - Graham Hutton
Programming with effects - Graham HuttonProgramming with effects - Graham Hutton
Programming with effects - Graham Hutton
Wen-Shih Chao
 
functions
functionsfunctions
functions
Makwana Bhavesh
 

Similar to Learn a language : LISP (20)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Matlab functions
Matlab functionsMatlab functions
Matlab functions
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
C basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kellaC basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kella
 
Matlab integration
Matlab integrationMatlab integration
Matlab integration
 
React native
React nativeReact native
React native
 
Programming with effects - Graham Hutton
Programming with effects - Graham HuttonProgramming with effects - Graham Hutton
Programming with effects - Graham Hutton
 
functions
functionsfunctions
functions
 

More from Devnology

What do we really know about the differences between static and dynamic types?
What do we really know about the differences between static and dynamic types?What do we really know about the differences between static and dynamic types?
What do we really know about the differences between static and dynamic types?
Devnology
 
Meetup at SIG: Meten is weten
Meetup at SIG: Meten is wetenMeetup at SIG: Meten is weten
Meetup at SIG: Meten is weten
Devnology
 
Software Operation Knowledge
Software Operation KnowledgeSoftware Operation Knowledge
Software Operation Knowledge
Devnology
 
Slides Felienne Hermans Symposium EWI
Slides Felienne Hermans Symposium EWISlides Felienne Hermans Symposium EWI
Slides Felienne Hermans Symposium EWI
Devnology
 
Devnology auteursrecht en open source 20130205
Devnology auteursrecht en open source 20130205Devnology auteursrecht en open source 20130205
Devnology auteursrecht en open source 20130205Devnology
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
Devnology
 
Hacking Smartcards & RFID
Hacking Smartcards & RFIDHacking Smartcards & RFID
Hacking Smartcards & RFID
Devnology
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
Devnology
 
Devnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software DevelopmentDevnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology
 
Devnology Back to School IV - Agility en Architectuur
Devnology Back to School IV - Agility en ArchitectuurDevnology Back to School IV - Agility en Architectuur
Devnology Back to School IV - Agility en Architectuur
Devnology
 
Devnology Back to School III : Software impact
Devnology Back to School III : Software impactDevnology Back to School III : Software impact
Devnology Back to School III : Software impact
Devnology
 
Devnology back toschool software reengineering
Devnology back toschool software reengineeringDevnology back toschool software reengineering
Devnology back toschool software reengineering
Devnology
 
Introduction to Software Evolution: The Software Volcano
Introduction to Software Evolution: The Software VolcanoIntroduction to Software Evolution: The Software Volcano
Introduction to Software Evolution: The Software Volcano
Devnology
 
Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011
Devnology
 
Devnology Coding Dojo 05-01-2011
Devnology Coding Dojo 05-01-2011Devnology Coding Dojo 05-01-2011
Devnology Coding Dojo 05-01-2011Devnology
 
Spoofax: ontwikkeling van domeinspecifieke talen in Eclipse
Spoofax: ontwikkeling van domeinspecifieke talen in EclipseSpoofax: ontwikkeling van domeinspecifieke talen in Eclipse
Spoofax: ontwikkeling van domeinspecifieke talen in Eclipse
Devnology
 
Experimenting with Augmented Reality
Experimenting with Augmented RealityExperimenting with Augmented Reality
Experimenting with Augmented Reality
Devnology
 
Unit testing and MVVM in Silverlight
Unit testing and MVVM in SilverlightUnit testing and MVVM in Silverlight
Unit testing and MVVM in Silverlight
Devnology
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkeling
Devnology
 
Devnology Fitnesse workshop
Devnology Fitnesse workshopDevnology Fitnesse workshop
Devnology Fitnesse workshop
Devnology
 

More from Devnology (20)

What do we really know about the differences between static and dynamic types?
What do we really know about the differences between static and dynamic types?What do we really know about the differences between static and dynamic types?
What do we really know about the differences between static and dynamic types?
 
Meetup at SIG: Meten is weten
Meetup at SIG: Meten is wetenMeetup at SIG: Meten is weten
Meetup at SIG: Meten is weten
 
Software Operation Knowledge
Software Operation KnowledgeSoftware Operation Knowledge
Software Operation Knowledge
 
Slides Felienne Hermans Symposium EWI
Slides Felienne Hermans Symposium EWISlides Felienne Hermans Symposium EWI
Slides Felienne Hermans Symposium EWI
 
Devnology auteursrecht en open source 20130205
Devnology auteursrecht en open source 20130205Devnology auteursrecht en open source 20130205
Devnology auteursrecht en open source 20130205
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Hacking Smartcards & RFID
Hacking Smartcards & RFIDHacking Smartcards & RFID
Hacking Smartcards & RFID
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Devnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software DevelopmentDevnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software Development
 
Devnology Back to School IV - Agility en Architectuur
Devnology Back to School IV - Agility en ArchitectuurDevnology Back to School IV - Agility en Architectuur
Devnology Back to School IV - Agility en Architectuur
 
Devnology Back to School III : Software impact
Devnology Back to School III : Software impactDevnology Back to School III : Software impact
Devnology Back to School III : Software impact
 
Devnology back toschool software reengineering
Devnology back toschool software reengineeringDevnology back toschool software reengineering
Devnology back toschool software reengineering
 
Introduction to Software Evolution: The Software Volcano
Introduction to Software Evolution: The Software VolcanoIntroduction to Software Evolution: The Software Volcano
Introduction to Software Evolution: The Software Volcano
 
Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011
 
Devnology Coding Dojo 05-01-2011
Devnology Coding Dojo 05-01-2011Devnology Coding Dojo 05-01-2011
Devnology Coding Dojo 05-01-2011
 
Spoofax: ontwikkeling van domeinspecifieke talen in Eclipse
Spoofax: ontwikkeling van domeinspecifieke talen in EclipseSpoofax: ontwikkeling van domeinspecifieke talen in Eclipse
Spoofax: ontwikkeling van domeinspecifieke talen in Eclipse
 
Experimenting with Augmented Reality
Experimenting with Augmented RealityExperimenting with Augmented Reality
Experimenting with Augmented Reality
 
Unit testing and MVVM in Silverlight
Unit testing and MVVM in SilverlightUnit testing and MVVM in Silverlight
Unit testing and MVVM in Silverlight
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkeling
 
Devnology Fitnesse workshop
Devnology Fitnesse workshopDevnology Fitnesse workshop
Devnology Fitnesse workshop
 

Recently uploaded

RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 

Recently uploaded (20)

RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 

Learn a language : LISP

  • 1. Learn a language: Clojure by Tijs van der Storm Preliminaries Install Eclipse, if you haven’t already. To get a “main-stream” IDE for Clojure, install the CounterClockwise plugin for Eclipse. I use it with Eclipse Indigo, but I have no idea whether other versions will work too. The webpage for the plugin can be found here: http://code.google.com/p/counterclockwise/. Use the Eclipse help menu to install extra software, add the update site: http://ccw.cgrand.net/updatesite/. Select the Clojure plugin. Next, accept, next, finish, restart Eclipse. Then File->New… select Clojure project. Finish. To create a file, right-click on the project, select New->Other- >Clojure namespace. To load/start a REPL (Read-Eval-Print-Loop) for the file, right-click the editor, and select load into REPL. Your functions are now accessible in the REPL. Some notes on the IDE: Command history is accessed through Ctrl-up and -down. In an editor, check the context menu for shortcuts to (re)load the current file. Clojure resources Main site: http://www.clojure.org Quickref of clojure.core: http://clojuredocs.org/quickref/Clojure%20Core Index of clojure.core: http://clojuredocs.org/clojure_core Exercises Warming up Type the following expression in the REPL. (print "Hello world!") (+ 1 2) (+ 1 2 3 4) * (map (fn [x] (+ x 2)) [1 2 3 4]) (def f (fn [x] (+ x 2))) (defn g [x] (+ x 2)) (map f [1 2 3 4])) (vec (map f [1 2 3 4])))
  • 2. (vec (map f [1 2 3 4]))) (reduce * [1 2 3 4]) (if (> 2 1) 'yes 'no) Quoting '() '4 '(+ 3 4) '[Hello world!] (quote (+ 3 x)) (list '+ 3 x) `(list '+ 3 x) (let [x 3] `(+ 3 ~x)) (let [x '(4 5 6)] `(+ 3 ~@x)) (let [x '(4 5 6)] (concat (list '+ 3) x)) Functional programming 1. Write the factorial function. 2. Implement the Fizz Buzz Test (see C2 http://c2.com/cgi/wiki?FizzBuzzTest). Tip: use doseq and range . 3. Write the power function using recursion. 4. Write the power function using squaring (see Wikipedia http://en.wikipedia.org/wiki/Exponentiation_by_squaring) 5. Write the power function using reduce and repeat . Macro programming In Clojure, a macro is defined using defmacro : (defmacro m [a1 … an] body) Here, m is the name of macro, a1 … an are the formal parameters and body is the body of the macro. Macros are functions that return code. How the result is created does not matter, but it is typical to use the quasiquote (backtick, `), unquote ( ~ ) and unquote splicing ( ~@ ). Note that when a macro is invoked (m e1 … en) , the argument expressions e1 … en are not evaluated. In other words, the formal parameters a1 … an of m are bound to the code trees of e1 … en . For instance, when calling (m (+ 1 2)) , a1 is bound to '(+ 1 2) and not to 3 . Tips for debugging macros: Use macroexpand and macroexpand-1 with a quoted macro invocation as argument to inspect what a top-level macro expands to.
  • 3. To see complete expansion of a macro, first issue (use 'clojure.walk) at the REPL prompt, then you can use macroexpand-all . Assert statement Write a macro that implements an assert statement, as found in Java. The macro should be called as follows: (assert* cond "some message") The result of assert* should be nil). If the condition cond fails (i.e., returns false or nil ) an exception should be thrown with a message containing the literal expression cond and the label string. Use throw to throw an exception, which can be created as follows (Exception. "some message") . Use the str function to concatenate strings. NB: the failing expression should be in the message. Tip: unquotes ( ~ ) can be in quotes ( ' )… Quiz Does assert* have to be a macro? If so why? If not, how would you implement it? Aside Practical Common Lisp devotes a chapter to writing a simple unit-test framework using macros: http://www.gigamonkeys.com/book/practical-building-a-unit-test-framework.html Let The let construct to introduce local variables is a built-in special form in Clojure. However, it is well-known that let can be implemented as a macro: an invocation of let expands to a function application. Write such a macro. Your version of let ( let* ) should expand as follows: (let* [var exp] body) => ((fn [var] body) exp) To simplify the exercise, you may assume that let only binds a single variable. If this is too simple, implement another version that supports multiple bindings. Times
  • 4. Times Write a macro times that takes an expression e and a number n and expands to a do form that just executes the expression n times. E.g.: (times 5 'hello) => (do 'hello 'hello 'hello 'hello 'hello) Tip: use the splicing unquote ~@ in combination with the core function repeat . Note that repeat generates an (lazily) infinite sequence, you have to provide the number of repetitions. Special power Partial evaluation is a program optimization technique that can be applied if certain arguments to a function are statically known. A traditional example is the power function. Often, the exponent argument ( n in (power x n) ) is statically known. Can we specialize the power function for a fixed n ? Partial evaluation in general is not for the faint of heart, but using macros we can do this specifically for power. The goal is to write a macro that generates the code for a power function that is specialized for some n . Let’s call it gen-power . Now, if (gen-power 3) returns a function f , then it should hold that (= (f x) (power x 3)) for all x . Here’s an example of what the invocation (gen-power 3) could expand to: (fn* ([x] (clojure.core/* x (clojure.core/* x (clojure.core/* x 1))))) NB: fn* is an internal form Clojure to represent functions. Note that the * function has been qualified with the namespace it is defined in. In the macro you can just use the normal fn and * to generate code. Tips Split the solution in two parts: 1. The top-level macro creates the function and calls a sub-function (gen-body 'x n) , where x represents the name of the parameter of the created function, and where n is the exponent. 2. The gen-body function recursively creates an expression to multiply x n times. Quiz Argue why the specialized power functions produced by gen-power would/should be faster than the general power function.
  • 5. Computing derivatives Check out this page to refresh your derivative chops: http://en.wikipedia.org/wiki/Derivative In this exercise, the goal is to compute the derivative of restricted, but otherwise ordinary Clojure functions. The restrictions are: Functions take only 1 argument. The body of the function can only use * , + , the formal parameter of the function, and constant numbers. You may assume both * and + only have two arguments (although Clojure supports an arbitrary number). Basically, such functions describe simple polynomials. An example is the following: (fn [x] (+ (* 3 (* x x)) (+ (* 2 x) 1)))) The derivative of this function is: (fn [x] (+ (* 6 x)) 2)) The exercise is to write a macro that returns and expression that computes this function. NB: this does not mean that it is syntactically the same as the derivative shown above; it should however give the same answers for the same inputs. The macro is invoked as follows: (deriv (fn [x] (+ (* 3 (* x x)) (+ (* 2 x) 1))))) Tips Split your solution in two parts: 1. The top-level macro that analyzes the fn argument to obtain the name of the parameter and the body expression, passes it to 2), and upon return constructs a new fn with the same parameter. 2. The helper function diff that receives and expression e and a variable name v which computes the derivative expression. Some useful functions: (number? x) : returns true if x is a number. (symbol? x) : returns true if x is a symbol.
  • 6. (first x) , (second x) : return the first resp. second elements of a collection (vector or list) x . (nth x n) : return the n -th element of a collection x . (cond c1 e1 … cn en :else e) : cascading conditional; finds the first ci that evaluates to true and evaluates ei . If no ci is found, evaluates e .