Practical: A Simple Database
* In this chapter you'll write a simple database for keeping track of CDs.
* Common Lisp provides three distinct kinds of operators: functions, macros, and special operators.
CDs and Records
* To keep track of CDs that need to be ripped to MP3s and which CDs should be
ripped first, each record in the database will contain the title and artist
of the CD, a rating of how much the user likes it, and a flag saying whether
it has been ripped.
* need a way to represent a single database record.
* user defined class - CLOS ( Common Lisp Object System)
CL-USER> (list 1 2 3)
(1 2 3)
* A plist is a list where every other element, starting with the first, is a
symbol that describes what the next element in the list is. Symbol can be
thought of as a name.
* For the symbols that name the fields in the CD database, you can use a particular kind of symbol, called a keyword symbol.
CL-USER> (list :a 1 :b 2 :c 3)
(:A 1 :B 2 :C 3)
* function GETF, which takes a plist and a symbol and returns the value in the
plist following the symbol.
CL-USER> (getf (list :a 1 :b 2 :c 3) :c)
3
* make-cd that will take the four fields as arguments and return a plist
representing that CD.
CL-USER> (defun make-cd(title artist rating ripped)
(list :title title :artist artist :rating rating :ripped ripped))
MAKE-CD
CL-USER>
* DEFUN tells us that this form is defining a new function.
* When make-cd is called, the arguments passed to the call will be bound to the variables in the parameter list. For instance, to make a record for the CD Roses by Kathy Mattea, you might call make-cd like this:
CL-USER> (make-cd "Roses" "Kathy Mattea" 7 t)
(:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T)
CL-USER>
Filling CDs.
* Larger Constructs to hold records.
* Also for simplicity you can use a global variable, *db*, which you can
define with the DEFVAR macro. The asterisks (*) in the name are a Lisp
naming convention for global variables.
* You can use the PUSH macro to add items to *db*. But it's probably a good idea to abstract things a tiny bit, so you should define a function add-record that adds a record to the database.
CL-USER> (defun add-record (cd) (push cd *db*))
ADD-RECORD
* add-record and make-cd together to add CDs to the database.
CL-USER> (add-record (make-cd "Fly" "Dixie Chicks" 8 t))
((:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T))
CL-USER> (add-record (make-cd "Roses" "Kathy Mattea" 7 t))
((:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T))
CL-USER> (add-record (make-cd "Home" "Dixie Chicks" 9 t))
((:TITLE "Home" :ARTIST "Dixie Chicks" :RATING 9 :RIPPED T)
(:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T))
CL-USER>
* Current value of *db* by typing *db*
CL-USER> *db*
* dump-db function that dumps out the database in a more human-readable
format.
CL-USER> (defun dump-db()
(dolist (cd *db*)
(format t "~{~a:~10t~a~%~}~%" cd)))
DUMP-DB
CL-USER>
* looping over all the elements of *db* with the DOLIST macro, binding each element to the variable cd in turn. For each value of cd, you use the FORMAT function to print it.
* In format, t is shorthand for the stream *standard-output*.
* Format directives start with ~ (much the way printf's directives start with %).
-----
One of the coolest FORMAT directives is the ~R directive. Ever want to know
how to say a really big number in English words? Lisp knows.
CL-USER> (format nil "~R" 42424242424242424242424242424242424242424242424242)
"forty-two quindecillion, four hundred and twenty-four quattuordecillion, two hundred and forty-two tredecillion, four hundred and twenty-four duodecillion, two hundred and forty-two undecillion, four hundred and twenty-four decillion, two hundred and forty-two nonillion, four hundred and twenty-four octillion, two hundred and forty-two septillion, four hundred and twenty-four sextillion, two hundred and forty-two quintillion, four hundred and twenty-four quadrillion, two hundred and forty-two trillion, four hundred and twenty-four billion, two hundred and forty-two million, four hundred and twenty-four thousand, two hundred and forty-two"
CL-USER>
----
* ~a directive is the aesthetic directive; it means to consume one argument
and output it in a human-readable form. This will render keywords without
the leading : and strings without quotation marks.
CL-USER> (format t "~a" "Dixie Chicks")
Dixie Chicks
NIL
CL-USER> (format t "~a" :title)
TITLE
NIL
CL-USER>
* The ~t directive is for tabulating. The ~10t tells FORMAT to emit enough spaces to move to the tenth column before processing the next ~a. A ~t doesn't consume any arguments.
CL-USER> (format t "~a:~10t~a" :artist "Dixie Chicks")
ARTIST: Dixie Chicks
NIL
CL-USER>
* When FORMAT sees ~{ the next argument to be consumed must be a list. FORMAT loops over that list, processing the directives between the ~{ and ~}.
* The ~% directive doesn't consume any arguments but tells FORMAT to emit a newline.
* we could have removed dolist macro call and used the format directive
itself:
CL-USER> (defun dump-db()
(format t "~{~{~a:~10t~a~%~}~%~}" *db*))
DUMP-DB
CL-USER>
Improving User Interaction.
* need some way to prompt the user for a piece of information and read it.
CL-USER> (defun prompt-read(prompt)
(format *query-io* "~a: " prompt)
(force-output *query-io*)
(read-line *query-io*))
PROMPT-READ
CL-USER>
* format to emit the prompt.
* FORCE-OUTPUT is necessary in some implementations to ensure that Lisp doesn't wait for a newline.
* read a single line of text with the aptly named READ-LINE function
* query-io is a global variable, can be recognized by the *query-io* naming.
combing make-cd with prompt-read
CL-USER> (defun prompt-for-cd()
(make-cd
(prompt-read "Title")
(prompt-read "Artist")
(prompt-read "Rating")
(prompt-read "Ripped [y/n]")))
PROMPT-FOR-CD
CL-USER>
* prompt-read returns a string, for converting the value to integer, lets use
lisp's parse-integer function.
* parse-integer takes an optional argument :junk-allowed which tells to relax
the conversion, if there is any exception.
* junk-allowed returns nill, if that cannot find the integer, to get over and
set it as 0, we use the or macro.
CL-USER> (parse-integer (prompt-read "Rating"))
Rating: 10
10
2
CL-USER> (parse-integer(prompt-read "Rating"):junk-allowed t)
Rating: 10
10
2
CL-USER> (parse-integer(prompt-read "Rating"):junk-allowed t)
Rating: Senthil
NIL
0
CL-USER> (or(parse-integer(prompt-read "Rating"):junk-allowed t)0)
Rating: Senthil
0
CL-USER>
* For y or n prompt, we can use common lisp function Y-OR-N-P, that will
reprompt the user till something starting with Y,y,N,n is entered.
So, the final prompt-for-cd will be:
CL-USER> (defun prompt-for-cd ()
(make-cd
(prompt-read "Title")
(prompt-read "Artist")
(or (parse-integer (prompt-read "Rating"):junk-allowd t)0)
(y-or-n-p "Ripped [y/n]")))
PROMPT-FOR-CD
* lets go for adding a bunch of CDs.
* You can use the simple form of the LOOP macro, which repeatedly executes a body of expressions until it's exited by a call to RETURN.
CL-USER> (defun add-cds()
(loop (add-record (prompt-for-cd))
(if (not (y-or-n-p "Another? [y/n]"))(return))))
ADD-CDS
CL-USER>
Saving and Loading the Database
*save-db function that takes a filename as an argument and saves the current state of the database.
CL-USER> (defun save-db (filename)
(with-open-file (out filename
:direction :output
:if-exists :supersede)
(with-standard-io-syntax
(print *db* out))))
SAVE-DB
CL-USER>
* WITH-OPEN-FILE macro opens a file, binds the stream to a variable, executes a set of expressions, and then closes the file. The list following WITH-OPEN-FILE is not function,but list of parameters to WITH-OPEN-FILE, defines the file to open to out stream, direction, output and if the file exists, then supersede.
After opening the file, we need to print the content using print command, which is different from formant, it prints in lisp recognizable objects which be read back by lisp-reader.
* WITH-STANDARD-IO-SYNTAX ensures that certain variables that affect the behavior of PRINT are set to their standard values.
CL-USER> (save-db "~/my-cds.db")
If open my-cds.db, we will find the output as in *db* at CL-USER> prompt.
The function to load the database back is similar.
CL-USER> (defun load-db(filename)
(with-open-file (in filename)
(with-standard-io-syntax
(setf *db* (read in)))))
LOAD-DB
CL-USER>
* The SETF macro is Common Lisp's main assignment operator. It sets its first argument to the result of evaluating its second argument.
Querying the Database
* query database.
Something LIKE (select :artist "Dixie Chicks")
* REMOVE-IF-NOT takes a predicate and a list and returns a copy of the list,
containing only the predicate.
* The predicate argument can be any function that accepts a single argument
* and returns a boolean value--NIL for false and anything else for true.
CL-USER> (remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)
CL-USER>
* The funny notation #' is shorthand for "Get me the function with the following name." Without the #', Lisp would treat evenp as the name of a variable and look up the value of the variable, not the function.
* We can also pass, remove-if-not, an anonymous function.
CL-USER> (remove-if-not #'(lambda (x)(= 0(mod x 2)))' (1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)
CL-USER>
* The anonymous function here is (lambda (x) (=0 (mod x 2))) which returns
true when x is even, else false.
* Note that lambda isn't the name of the function--it's the indicator you're defining an anonymous function.
* To select record using artist, we use the property of plist, getf, and equal
to compare and put them all together in a lambda expression.
CL-USER> (remove-if-not
#'(lambda (cd) (equal (getf cd :artist) "Dixie Chicks")) *db*)
((:TITLE "Home" :ARTIST "Dixie Chicks" :RATING 9 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T))
CL-USER>
* To wrap the whole expression in a function.
CL-USER> (defun select-by-artist (artist)
(remove-if-not
#'(lambda (cd) (equal (getf cd :artist)artist)) *db*))
SELECT-BY-ARTIST
CL-USER>
* Anonymous functions, embeds the required details like artist.
* More general select function, with Anonymous function at the next stage.
CL-USER> (defun select (selector-fn)
(remove-if-not selector-fn *db*))
SELECT
CL-USER> (select #'(lambda (cd) (equal (getf cd :artist) "Dixie Chicks")))
((:TITLE "Home" :ARTIST "Dixie Chicks" :RATING 9 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T))
CL-USER>
* Anonymous function creation can be wrapped up.
CL-USER> (defun artist-selector (artist)
#'(lambda (cd) (equal (getf cd :artist) artist)))
ARTIST-SELECTOR
CL-USER> (select (artist-selector "Dixie Chicks"))
((:TITLE "Home" :ARTIST "Dixie Chicks" :RATING 9 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T))
CL-USER>
* Write a general purpose, selector function generator, a function that,
depending upon what arguments is getting passed, will generate a selector
function for different fields, or different combination of fields.
*Keyword parameters
*Write functions with varying number of parameters, which are bound to the
corresponding arguments to the call to the function.
(defun foo (&key a b c) (list a b c))
The only difference is the &key at the beginning of the argument list. However, the calls to this new foo will look quite different. These are all legal calls with the result to the right of the ==>:
(foo :a 1 :b 2 :c 3) ==> (1 2 3)
(foo :c 3 :b 2 :a 1) ==> (1 2 3)
(foo :a 1 :c 3) ==> (1 NIL 3)
(foo) ==> (NIL NIL NIL)
* Need to differentiate between NIL assigned when no value passed vs
explicitly assigned NIL.
* To allow this, when you specify a keyword parameter you can replace the simple name with a list consisting of the name of the parameter, a default value, and another parameter name, called a supplied-p parameter.
* supplied-p parameter will set to true or false if an arugment was passed to
the function call.
(defun foo (&key a (b 20) (c 30 c-p)) (list a b c c-p))
Now the same calls from earlier yield these results:
(foo :a 1 :b 2 :c 3) ==> (1 2 3 T)
(foo :c 3 :b 2 :a 1) ==> (1 2 3 T)
(foo :a 1 :c 3) ==> (1 20 3 T)
(foo) ==> (NIL 20 30 NIL)
* A general selector function, based on the above discussions will be:
(defun where (&key title artist rating (ripped nil ripped-p))
#'(lambda (cd)
(and
(if title (equal (getf cd :title) title) t)
(if artist (equal (getf cd :artist) artist) t)
(if rating (equal (getf cd :rating) rating) t)
(if ripped-p (equal (getf cd :ripped) ripped) t))))
* Updating Existing Records--Another Use for WHERE
(defun update (selector-fn &key title artist rating (ripped nil ripped-p))
(setf *db*
(mapcar
#'(lambda (row)
(when (funcall selector-fn row)
(if title (setf (getf row :title) title))
(if artist (setf (getf row :artist) artist))
(if rating (setf (getf row :rating) rating))
(if ripped-p (setf (getf row :ripped) ripped)))
row) *db*)))
* CL-USER> (update (where :artist "Dixie Chicks") :rating 11)
NIL
* Function to delete rows.
(defun delete-rows (selector-fn)
(setf *db* (remove-if selector-fn *db*)))
* Remove Duplication and winning Big
* When a Lisp expression contains a call to a macro, instead of evaluating the arguments and passing them to the function, the Lisp compiler passes the arguments, unevaluated, to the macro code, which returns a new Lisp expression that is then evaluated in place of the original macro call.
* The main syntactic difference between a function and a macro is that you
* define a macro with DEFMACRO instead of DEFUN.
CL-USER>(defmacro backwards (expr) (reverse expr))
CL-USER> (backwards ("hello, world" t format))
hello, world
NIL
When the REPL started to evaluate the backwards expression, it recognized that backwards is the name of a macro. So it left the expression ("hello, world" t format) unevaluated, which is good because it isn't a legal Lisp form. It then passed that list to the backwards code. The code in backwards passed the list to REVERSE, which returned the list (format t "hello, world").
This is O.R.Senthil Kumaran's blogspot on programming and technical things. The title is a line from "Zen of Python".
PCL: A Practical Database
print and softspace in python
In python, whenever you use >>>print statement it will append a newline by default. If you don't want newline to be appended, you got use a comma at the end (>>>print 10,)
When, you have a list of characters and want them to be printed together a string using a for loop, there was observation that no matter what there was space coming between the characters. No split or join methods helped.
>>>list1=['a','b','c']
>>>for e in list1:
print e,
a b c
>>># Without whitespace it will look like.
>>>print "abc"
abc
The language reference says that print is designed to output a space before any object. And some search goes to find and that is controlled by softspace attribute of sys.stdout.
Way to print without leading space is using sys.stdout.write()
>>>import sys
>>>for e in list1:
sys.stdout.write(e)
abc
Reference manual says:
A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is "\n", or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.)
Not getting the last part as how you will write a empty string and use print not appending blank space in a single line
When, you have a list of characters and want them to be printed together a string using a for loop, there was observation that no matter what there was space coming between the characters. No split or join methods helped.
>>>list1=['a','b','c']
>>>for e in list1:
print e,
a b c
>>># Without whitespace it will look like.
>>>print "abc"
abc
The language reference says that print is designed to output a space before any object. And some search goes to find and that is controlled by softspace attribute of sys.stdout.
Way to print without leading space is using sys.stdout.write()
>>>import sys
>>>for e in list1:
sys.stdout.write(e)
abc
Reference manual says:
A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is "\n", or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.)
Not getting the last part as how you will write a empty string and use print not appending blank space in a single line
Sending SMS Messages Using Windows XP
I wanted this facility to send SMS via laptop keyboard connected via bluetooth to my mobile. It was very easy to setup. You got to use the Microsoft SMS sender software.
ngwallpaper
Got started with using code.google.com project hosting for ngwallpaper project. When you execute this python script, it fetches the wallpaper of the day from National Geographic site and sets it up as your Desktop Wallpaper.
Currently works on Windows platform with python windows extensions installs ( it uses SETDESTOPWALLPAPER attribute of a particular windows call).
Desirable features for ngwallpaper is 1) Platform agnostic (Windows, Linux, Mac) 2)More structure code. One present is just a start version 3)the program as a service or scheduled service which will run a particular time everyday. 4) Fix the windows set wallpaper issue where after few hours the wallpaper gets reset.
Currently works on Windows platform with python windows extensions installs ( it uses SETDESTOPWALLPAPER attribute of a particular windows call).
Desirable features for ngwallpaper is 1) Platform agnostic (Windows, Linux, Mac) 2)More structure code. One present is just a start version 3)the program as a service or scheduled service which will run a particular time everyday. 4) Fix the windows set wallpaper issue where after few hours the wallpaper gets reset.
scrapbook extention for firefox
At times I read the Netspeak column in The Hindu. A particular weekly issue, mentioned about Offline Browsing Tool for Firefox called Scrapbook. This solved my much desired feature of having pages offline in firefox. Internet explorer provides this feature wherein it cache the visited pages and when the user goes offline and try to browse, it loads up the page from the internal cache. This is a useful feature when Internet connection is costly and slow, and u want to visit the pages you browsed at your work place, to be browsed( usually good long articles to read) at home without connecting to internet.
Scrapbook extension for firefox, solves this limitation. Its sits a title bar, and on page am on, I can scrap it, so that will be available offline.
In the offline reading mode, I can add comments, highlight text, and search the pages as well.
Quite a good firefox extension.
Scrapbook extension for firefox, solves this limitation. Its sits a title bar, and on page am on, I can scrap it, so that will be available offline.
In the offline reading mode, I can add comments, highlight text, and search the pages as well.
Quite a good firefox extension.
Using Windows Modem Troubleshooter
I connect to internet using my laptop running Windows XP from home, using the BSNL dial-up connection over the Internal Conexant D110 MDC V.92 Modem. Past few days, I was unable to dial up, the dial up died with in few seconds, and I could not figure out the reason as well.
Followed the Windows Troubleshooter tool today, which asked me to check for correct protocol set at Internet Connection settings (TCP/IP), and suggested a step called "Show Terminal Window" in the Security tab of the Network Connections settings for the Modem Connection.
When Enabled and Dialed again, I am able to connect now. The problem is solved, but I am not yet to bottom of it.
Let me enjoy it now.
Followed the Windows Troubleshooter tool today, which asked me to check for correct protocol set at Internet Connection settings (TCP/IP), and suggested a step called "Show Terminal Window" in the Security tab of the Network Connections settings for the Modem Connection.
When Enabled and Dialed again, I am able to connect now. The problem is solved, but I am not yet to bottom of it.
Let me enjoy it now.
RSS Feeds with Syndication Icon
Lisp Notes -2. On REPL
Subsequent to Lisp Notes 1;these are my notes for the Chapter 2 "Lather, Rinse, Repeat: A Tour of the REPL" in the Practical Common Lisp Book
* Lisp provides an interactive read-eval-print loop.
* Lisp can be used in Automated Theorem proving, planning and scheduling and computer vision. Large scale battlefield simulation, automated planning and natural language interfaces.
* Help in EMACS, Press CTRL Key, type h, release CTRL key and press t. This key combination called key-chord is represented like this. C-t h
* Info system is available by C-h i
* C-h ? brings complete list.
* C-h k lets us type any key combination and lets us know the command which will be invoked.
* C-h w lets us enter the command and returns the corresponding key combination.
Crucial bit of emacs terminology is a Buffer. While working with EMACS, each file you edit will be represented by a different buffer, only one of which is current in any way.
Buffers:
* C-x b is command to switch to buffer.
Some key combinations may be available for switches to certain buffer.
For e.g. to switch to lisp source file.
* C-c C-z switch to buffer where you interact with lisp ( REPL)
CL-USER>
This is the lisp command prompt. Lisp reads the lines of lisp expressions evaluates them according to the rules of lisp and prints the result.
The endless cycle of reading, evaluating and printing is why it is called read-eval-print loop or REPL for short.
Its also refered to as top level, top level listner, lisp listner.
From REPL we can:
- Define or redefine variables, functions, classes and methods.
- Evaluate any lisp expression.
- Load files containing lisp source code or compiled code.
- compile other files or individual functions.
- Enter Debugger.
- Step through the code.
- Inspect the state of the individual lisp command.
CL-USER>10
10
R - Reads "10" and coverts to lisp object "10"
E - Evaluates to itself.
P - Prints "10"
CL-USER>(+ 2 3)
+ symbol is coverted to + function which takes 2 and 3 as parameters.
CL-USER>"hello,world"
"hello,world"
That was a "hello,world" value.
Format function:
Format takes a variable number of arguments, but the only two required to send the output a string.
CL-USER>(format t "hello,world")
"hello,world"
NIL
* t sends the output to stdout.
* NIL is the return value of the function.
CL-USER>(defun hello-world() (format t "hello,world"))
HELLO-WORLD
CL-USER>(hello-world)
hello,world
NIL
Saving the file:
* C-x C-f type the file name with extension as .lisp or .cl
* Inside the SLIME mode, C-c C-q invokes the command slime-close-parens-at-point which will insert as many closing paranthesis as necessary to match all the open paranthesis.
* To get the source file to lisp enviroment:
* C-c C-c ( slime-compile-defun)
Or switch the REPL Buffer:
* C-c C-z (directly from SLIME to REPL)
Or
* C-x b and all the buffer.
Make some changes and type again.
(defun hello-world()
(format t "Hello,World!"))
* C-c C-c
Or
* C-c C-z
(hello,world)
Hello,World!
NIL
Save the changes to hello.lisp by typing C-x C-s in EMACS which invokes (save-buffer)
Exit SLIME, which is in REPL type ',' -a comma.
Invoke again:
M-x slime
CL-USER>(hello-world)
Will got get invoke because REPL is not aware and it will put you in the debugger mode. pressing 'q' will exit the debugger.
CL-USER>(hello-world)
;Evaluation aborted
CL-USER>
Letting the REPL Know.
1) C-x b hello.lisp and then compling using C-c C-c
2) Load the whole file:
(load "hello.lisp")
; Loading file
T
T- means loaded correctly.
FASL - Fast Load file
(load(compile-file("hello.lisp"))
From the SLIME enviroment itself, the following features are available:
* C-c C-l (slime-load-file)
* C-c C-k to compile and load the file represented by the current buffer.
* Lisp provides an interactive read-eval-print loop.
* Lisp can be used in Automated Theorem proving, planning and scheduling and computer vision. Large scale battlefield simulation, automated planning and natural language interfaces.
* Help in EMACS, Press CTRL Key, type h, release CTRL key and press t. This key combination called key-chord is represented like this. C-t h
* Info system is available by C-h i
* C-h ? brings complete list.
* C-h k lets us type any key combination and lets us know the command which will be invoked.
* C-h w lets us enter the command and returns the corresponding key combination.
Crucial bit of emacs terminology is a Buffer. While working with EMACS, each file you edit will be represented by a different buffer, only one of which is current in any way.
Buffers:
* C-x b is command to switch to buffer.
Some key combinations may be available for switches to certain buffer.
For e.g. to switch to lisp source file.
* C-c C-z switch to buffer where you interact with lisp ( REPL)
CL-USER>
This is the lisp command prompt. Lisp reads the lines of lisp expressions evaluates them according to the rules of lisp and prints the result.
The endless cycle of reading, evaluating and printing is why it is called read-eval-print loop or REPL for short.
Its also refered to as top level, top level listner, lisp listner.
From REPL we can:
- Define or redefine variables, functions, classes and methods.
- Evaluate any lisp expression.
- Load files containing lisp source code or compiled code.
- compile other files or individual functions.
- Enter Debugger.
- Step through the code.
- Inspect the state of the individual lisp command.
CL-USER>10
10
R - Reads "10" and coverts to lisp object "10"
E - Evaluates to itself.
P - Prints "10"
CL-USER>(+ 2 3)
+ symbol is coverted to + function which takes 2 and 3 as parameters.
CL-USER>"hello,world"
"hello,world"
That was a "hello,world" value.
Format function:
Format takes a variable number of arguments, but the only two required to send the output a string.
CL-USER>(format t "hello,world")
"hello,world"
NIL
* t sends the output to stdout.
* NIL is the return value of the function.
CL-USER>(defun hello-world() (format t "hello,world"))
HELLO-WORLD
CL-USER>(hello-world)
hello,world
NIL
Saving the file:
* C-x C-f type the file name with extension as .lisp or .cl
* Inside the SLIME mode, C-c C-q invokes the command slime-close-parens-at-point which will insert as many closing paranthesis as necessary to match all the open paranthesis.
* To get the source file to lisp enviroment:
* C-c C-c ( slime-compile-defun)
Or switch the REPL Buffer:
* C-c C-z (directly from SLIME to REPL)
Or
* C-x b and all the buffer.
Make some changes and type again.
(defun hello-world()
(format t "Hello,World!"))
* C-c C-c
Or
* C-c C-z
(hello,world)
Hello,World!
NIL
Save the changes to hello.lisp by typing C-x C-s in EMACS which invokes (save-buffer)
Exit SLIME, which is in REPL type ',' -a comma.
Invoke again:
M-x slime
CL-USER>(hello-world)
Will got get invoke because REPL is not aware and it will put you in the debugger mode. pressing 'q' will exit the debugger.
CL-USER>(hello-world)
;Evaluation aborted
CL-USER>
Letting the REPL Know.
1) C-x b hello.lisp and then compling using C-c C-c
2) Load the whole file:
(load "hello.lisp")
; Loading file
T
T- means loaded correctly.
FASL - Fast Load file
(load(compile-file("hello.lisp"))
From the SLIME enviroment itself, the following features are available:
* C-c C-l (slime-load-file)
* C-c C-k to compile and load the file represented by the current buffer.
AI Class Notes - 2
Notes from AI Class
Any solution goes from (0,0) state to (goal state).
- Reasoning.
- AI stands for positive thinking.*
- Chess playing, alternative choices, multiple choices.
- Humans can think simultaneously different things.
- Machine intelligence revolution.
What is A.I?
Artificial: Produced by art. Not genuine or natural, not pertaining to
the sense of matter.
Synonymous: Synthetic, fictitious, pretend, simulated, spurious,
unnatural.
Antonyms: Actual, genuine, honest, real, natural, truthful and
unaffected.
Intelligence: Endowed with a faculty of reasoning, quick of mind, well
informed and communicative.
* Marvin Minsky's initial writings provide a very good introduction.
* Do plants think?
Objectives of AI?
Primary Goal: To Make the computers smart. (CS)
Secondary Goal: To understand the nature of human intelligence.(psychologist)
Entreprenuers" To make machines more useful and economical (eventually
replace humans)
Japanese tried to create machines that will help humans when they fail.
* Fuzzy Logic in washing machines.
* Inacessible to humans? Machines with intelligence needed.
Normal missiles will be shot, but missiles with intelligence have chances of
hitting the target.
Virtual reality system help in designing the A.I system.
What is an A.I problem today may not be same 20 years down.
Definition:
AI is the study of how to make computers do things at which at the moment,
human beings are better.
(2) AI is the study of mental faculties through the use of computational
methods.
Questions:
1) What are our own underlying assumptions about intelligence?
2) At what level of details are we going to model and mimic intelligence?
3) What kind of tools and techniques we have at present for study of AI?
4) How will we know that we have succeeded in building an intelligent system?
5) What computers can and cannot do?
6) Can machines think?
7) Can a machine fool a human being into thinking that (s)he chatting with
another human being?
Computational methods:
- Number crunching.
- Huristic programming.
- Automatic programming.
8) Why we think that machines cannot?
9) For that matter, do humans think? and How do we think?
Chart:
A Modern AI Lab.
* Reasoning about objects.
* Programming [ lisp, prolog ]
* Architecture [ fifth generation, parallel]
* Design and Analysis Systems [ knowledge based expert AI
systems, decision support systems]
* Speech and Language
* Learning.
* Vision and Speech
* Robotics
Intelligent Behaviour:
Use of huristics: using some rules of thumb for deciding any of the several
alternative choices.
Huristic:
Best first search, breadth first search and depth first search.
- Huristic should help us in dramatically reducing the search for solution in
the large problem spaces.
- No guarantee of optimal solution.
Two approaches to Designing AI Based Computers.
Top-Down Approach
A.I. Application
*
* Predicate Logic
* Frames
* Semantic Nets.
* Knowledge Representation
A.I. Languages
* Lisp
* Prolog
* Smalltalk
Bottom Up Approach
Computing Model
* Control Flow
* Data Structure
* Data
A.I Architecture
Assignment:
To Reach IISc from your Home.
Parameters: Vehicle, Mode of transport, Map.
Time and shortest path constraints.
Between own vehicle and public transport, which one is preferable?
Knowledge:
Search Engine, algorithm is intelligence and database is knowledge.
Human information processing.
All knowledge structures are Tree Structures.
Reasoing:
Reasoning refers to the different kinds of activities:
- Drawing conclusions from different set of facts.
- Diagnosing possible cause of conditions.
- Making assumption about a situation.
- Analysis of organizing facts and data about problem
- Solving a problem or a puzzle.
- Arguing with a person with a particular point of view.
Classification of Reasoning activities:
Based on Degree of perception
* Deductive reasoning.
* Inductive reasoning.
* Default reasoning.
Based on level of reasoning.
* Problem level reasoning.
* Meta level reasning.
Based on generality
* Casual
* Common Sense.
* von monotonic
* Plausible
* special
* Temporal
* Reasoning systems involve the representation of information and word.
Any solution goes from (0,0) state to (goal state).
- Reasoning.
- AI stands for positive thinking.*
- Chess playing, alternative choices, multiple choices.
- Humans can think simultaneously different things.
- Machine intelligence revolution.
What is A.I?
Artificial: Produced by art. Not genuine or natural, not pertaining to
the sense of matter.
Synonymous: Synthetic, fictitious, pretend, simulated, spurious,
unnatural.
Antonyms: Actual, genuine, honest, real, natural, truthful and
unaffected.
Intelligence: Endowed with a faculty of reasoning, quick of mind, well
informed and communicative.
* Marvin Minsky's initial writings provide a very good introduction.
* Do plants think?
Objectives of AI?
Primary Goal: To Make the computers smart. (CS)
Secondary Goal: To understand the nature of human intelligence.(psychologist)
Entreprenuers" To make machines more useful and economical (eventually
replace humans)
Japanese tried to create machines that will help humans when they fail.
* Fuzzy Logic in washing machines.
* Inacessible to humans? Machines with intelligence needed.
Normal missiles will be shot, but missiles with intelligence have chances of
hitting the target.
Virtual reality system help in designing the A.I system.
What is an A.I problem today may not be same 20 years down.
Definition:
AI is the study of how to make computers do things at which at the moment,
human beings are better.
(2) AI is the study of mental faculties through the use of computational
methods.
Questions:
1) What are our own underlying assumptions about intelligence?
2) At what level of details are we going to model and mimic intelligence?
3) What kind of tools and techniques we have at present for study of AI?
4) How will we know that we have succeeded in building an intelligent system?
5) What computers can and cannot do?
6) Can machines think?
7) Can a machine fool a human being into thinking that (s)he chatting with
another human being?
Computational methods:
- Number crunching.
- Huristic programming.
- Automatic programming.
8) Why we think that machines cannot?
9) For that matter, do humans think? and How do we think?
Chart:
A Modern AI Lab.
* Reasoning about objects.
* Programming [ lisp, prolog ]
* Architecture [ fifth generation, parallel]
* Design and Analysis Systems [ knowledge based expert AI
systems, decision support systems]
* Speech and Language
* Learning.
* Vision and Speech
* Robotics
Intelligent Behaviour:
Use of huristics: using some rules of thumb for deciding any of the several
alternative choices.
Huristic:
Best first search, breadth first search and depth first search.
- Huristic should help us in dramatically reducing the search for solution in
the large problem spaces.
- No guarantee of optimal solution.
Two approaches to Designing AI Based Computers.
Top-Down Approach
A.I. Application
*
* Predicate Logic
* Frames
* Semantic Nets.
* Knowledge Representation
A.I. Languages
* Lisp
* Prolog
* Smalltalk
Bottom Up Approach
Computing Model
* Control Flow
* Data Structure
* Data
A.I Architecture
Assignment:
To Reach IISc from your Home.
Parameters: Vehicle, Mode of transport, Map.
Time and shortest path constraints.
Between own vehicle and public transport, which one is preferable?
Knowledge:
Search Engine, algorithm is intelligence and database is knowledge.
Human information processing.
All knowledge structures are Tree Structures.
Reasoing:
Reasoning refers to the different kinds of activities:
- Drawing conclusions from different set of facts.
- Diagnosing possible cause of conditions.
- Making assumption about a situation.
- Analysis of organizing facts and data about problem
- Solving a problem or a puzzle.
- Arguing with a person with a particular point of view.
Classification of Reasoning activities:
Based on Degree of perception
* Deductive reasoning.
* Inductive reasoning.
* Default reasoning.
Based on level of reasoning.
* Problem level reasoning.
* Meta level reasning.
Based on generality
* Casual
* Common Sense.
* von monotonic
* Plausible
* special
* Temporal
* Reasoning systems involve the representation of information and word.
Marvin Minsky on AI
Found this post at /. which references the podcasts of Marvin Minsky on AI, but I am unable to locate them.
Found two comments which are very insightful and written by people whose thoughts were along the same direction as our discussions in proficience course over the weekends.
Quotes:
While much of the "traditional AI" hype could be considered dead, robotics is continuing to advance, and much symbolic AI research has evolved into data-driven statistical techniques. So while the top-down ideas that the older AI researches didn't pan out yet, bottom-up techniques will still help close the gap.
Also, you have to remember that AI is pretty much defined as "the stuff we don't know how to do yet". Once we know how to do it, then people stop calling it AI, and then wonder "why can't we do AI?" Machine vision is doing everything from factory inspections to face recognition, we have voice recognition on our cell phones, and context-sensitive web search is common. All those things were considered AI not long ago. Calculators were once even called mechanical brains. by SnowZero.
----
Personally I don't think it's quantum computers that will be the breakthrough, but simply a different architecture for conventional computers. Let me go on a little tangent here.
Now that we've reached the limits of the Von Neumann architecture [wikipedia.org], we're starting to see a new wave of innovation in CPU design. The Cell is part of that, but also the stuff ATI [amd.com] and NVIDIA [nvidia.com] are doing is also very interesting. Instead of one monolithic processor connected to a giant memory through a tiny bottleneck, processors of the future will be a grid of processing elements interleaved with embedded memory in a network structure. Almost like a Beowulf cluster on a chip.
People are worried about how conventional programs will scale to these new architectures, but I believe they won't have to. Code monkeys won't be writing code to spawn thousands of cooperating threads to run the logic of a C++ application faster. Instead, PhDs will write specialized libraries to leverage all that parallel processing power for specific algorithms. You'll have a raytracing library, an image processing library, an FFT library, etc. These specialized libraries will have no problem sponging up all the excess computing resources, while your traditional software continues to run on just two or three traditional cores.
Back on the subject of AI, my theory is that these highly parallel architectures will be much more suited to simulating the highly parallel human brain. They will excel at the kinds pattern matching tasks our brains eat for breakfast. Computer vision, speech recognition, natural language processing; all of these will be highly amenable to parallelization. And it is these applications which will eventually prove the worth of non-traditional architectures like Intel's 80-core chip. It may still be a long time before the sentient computer is unveiled, but I think we will soon finally start seeing real-world AI applications like decent automated translation, image labeling, and usable stereo vision for robot navigation. Furthermore, I predict that Google will be on the forefront of this new AI revolution, developing new algorithms to truly understand web content to reject spam and improve rankings.
by Modeless
Found two comments which are very insightful and written by people whose thoughts were along the same direction as our discussions in proficience course over the weekends.
Quotes:
While much of the "traditional AI" hype could be considered dead, robotics is continuing to advance, and much symbolic AI research has evolved into data-driven statistical techniques. So while the top-down ideas that the older AI researches didn't pan out yet, bottom-up techniques will still help close the gap.
Also, you have to remember that AI is pretty much defined as "the stuff we don't know how to do yet". Once we know how to do it, then people stop calling it AI, and then wonder "why can't we do AI?" Machine vision is doing everything from factory inspections to face recognition, we have voice recognition on our cell phones, and context-sensitive web search is common. All those things were considered AI not long ago. Calculators were once even called mechanical brains. by SnowZero.
----
Personally I don't think it's quantum computers that will be the breakthrough, but simply a different architecture for conventional computers. Let me go on a little tangent here.
Now that we've reached the limits of the Von Neumann architecture [wikipedia.org], we're starting to see a new wave of innovation in CPU design. The Cell is part of that, but also the stuff ATI [amd.com] and NVIDIA [nvidia.com] are doing is also very interesting. Instead of one monolithic processor connected to a giant memory through a tiny bottleneck, processors of the future will be a grid of processing elements interleaved with embedded memory in a network structure. Almost like a Beowulf cluster on a chip.
People are worried about how conventional programs will scale to these new architectures, but I believe they won't have to. Code monkeys won't be writing code to spawn thousands of cooperating threads to run the logic of a C++ application faster. Instead, PhDs will write specialized libraries to leverage all that parallel processing power for specific algorithms. You'll have a raytracing library, an image processing library, an FFT library, etc. These specialized libraries will have no problem sponging up all the excess computing resources, while your traditional software continues to run on just two or three traditional cores.
Back on the subject of AI, my theory is that these highly parallel architectures will be much more suited to simulating the highly parallel human brain. They will excel at the kinds pattern matching tasks our brains eat for breakfast. Computer vision, speech recognition, natural language processing; all of these will be highly amenable to parallelization. And it is these applications which will eventually prove the worth of non-traditional architectures like Intel's 80-core chip. It may still be a long time before the sentient computer is unveiled, but I think we will soon finally start seeing real-world AI applications like decent automated translation, image labeling, and usable stereo vision for robot navigation. Furthermore, I predict that Google will be on the forefront of this new AI revolution, developing new algorithms to truly understand web content to reject spam and improve rankings.
by Modeless
Subscribe to:
Posts (Atom)