question_id
int64 1.99k
74.6M
| answer_id
int64 4.76k
74.6M
| title
stringlengths 20
144
| question
stringlengths 22
4.09k
| answer
stringlengths 24
4.1k
|
---|---|---|---|---|
1,988 | 63,737 | How far can LISP macros go? | I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby?
Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language.
| That's a really good question.
I think it's nuanced but definitely answerable:
Macros are not stuck in s-expressions. See the LOOP macro for a very complex language written using keywords (symbols). So, while you may start and end the loop with parentheses, inside it has its own syntax.
Example:
(loop for x from 0 below 100
when (even x)
collect x)
That being said, most simple macros just use s-expressions. And you'd be "stuck" using them.
But s-expressions, like Sergio has answered, start to feel right. The syntax gets out of the way and you start coding in the syntax tree.
As for reader macros, yes, you could conceivably write something like this:
#R{
ruby.code.goes.here
}
But you'd need to write your own Ruby syntax parser.
You can also mimic some of the Ruby constructs, like blocks, with macros that compile to the existing Lisp constructs.
#B(some lisp (code goes here))
would translate to
(lambda () (some lisp (code goes here)))
See this page for how to do it.
|
4,724 | 4,755 | Why should I learn Lisp? | I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it.
I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language.
Is there a commercial killer-app out there that's been written in Lisp ?
| One of the main uses for Lisp is in Artificial Intelligence. A friend of mine at college took a graduate AI course and for his main project he wrote a "Lights Out" solver in Lisp. Multiple versions of his program utilized slightly different AI routines and testing on 40 or so computers yielded some pretty neat results (I wish it was online somewhere for me to link to, but I don't think it is).
Two semesters ago I used Scheme (a language based on Lisp) to write an interactive program that simulated Abbott and Costello's "Who's on First" routine. Input from the user was matched against some pretty complicated data structures (resembling maps in other languages, but much more flexible) to choose what an appropriate response would be. I also wrote a routine to solve a 3x3 slide puzzle (an algorithm which could easily be extended to larger slide puzzles).
In summary, learning Lisp (or Scheme) may not yield many practical applications beyond AI but it is an extremely valuable learning experience, as many others have stated. Programming in a functional language like Lisp will also help you think recursively (if you've had trouble with recursion in other languages, this could be a great help).
|
6,512 | 6,566 | How to implement continuations? | I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal.
What is the simplest way to implement continuations for Scheme in C?
| I remember reading an article that may be of help to you: Cheney on the M.T.A. :-)
Some implementations of Scheme I know of, such as SISC, allocate their call frames on the heap.
@ollie: You don't need to do the hoisting if all your call frames are on the heap. There's a tradeoff in performance, of course: the time to hoist, versus the overhead required to allocate all frames on the heap. Maybe it should be a tunable runtime parameter in the interpreter. :-P
|
10,149 | 10,161 | How do I bind a regular expression to a key combination in emacs? | For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.
What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.
What I've been doing:
M-C-s ^.*Table\(\(.*\n\)*?GO\)
Note, I used newline above, but I've found that for isearch-forward-regexp, you really need to replace the \n in the regular expression with the result of C-q Q-j. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.
How can I bind this to a key combination?
I vaguely understand that I need to create an elisp function which executes isearch-forward-regexp with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.
How can I bind a regular expression to a key combination in emacs?
Mike Stone had the best answer so far -- not exactly what I was looking for but it worked for what I needed
Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with C-x e. (i.e., if I reboot emacs and then type M-x macro-name, and then C-x e, I get a message in the minibuffer like 'no last kbd macro' or something similar)
@Mike Stone - Thanks for the information. I tried creating a macro like so:
C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use isearch-forward-regexp. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?
Edit: It looks like I can use macros to do what I want, I just have to think outside the box of isearch-forward-regexp. I'll try what you suggested.
| You can use macros, just do C-x ( then do everything for the macro, then C-x ) to end the macro, then C-x e will execute the last defined macro. Then, you can name it using M-x name-last-kbd-macro which lets you assign a name to it, which you can then invoke with M-x TESTIT, then store the definition using M-x insert-kbd-macro which will put the macro into your current buffer, and then you can store it in your .emacs file.
Example:
C-x( abc *return* C-x)
Will define a macro to type "abc" and press return.
C-xeee
Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more).
M-x name-last-kbd-macro testit
Names the macro to "testit"
M-x testit
Executes the just named macro (prints "abc" then return).
M-x insert-kbd-macro
Puts the following in your current buffer:
(fset 'testit
[?a ?b ?c return])
Which can then be saved in your .emacs file to use the named macro over and over again after restarting emacs.
|
23,166 | 23,179 | What's a good beginning text on functional programming? | I like to study languages outside my comfort zone, but I've had a hard time finding a place to start for functional languages. I heard a lot of good things about Structure and Interpretations of Computer Programs, but when I tried to read through it a couple of years ago it just seemed to whiz over my head. I do way better with books than web sites, but when I visit the local book store the books on LISP look kind of scary.
So what's a good starting point? My goal is to be able to use a functional programming language to solve simple problems in 6 months or so, and the ability to move to more advanced topics, recognize when a functional language is the right tool for the job, and use the language to solve more problems over the course of 2-3 years. I like books that are heavy on examples but also include challenges to work through. Does such a thing exist for functional languages?
| The Little Schemer teaches recursion really well, and it's fun and simple to read.
I also liked The Scheme Programming Language for a broader introduction into the language.
|
31,561 | 31,603 | Keeping CL and Scheme straight in your head | Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2. Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into. Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all. Took me a bit to remember I wanted mapcar, not map. Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all.
So, pointers on how to minimize this short of picking one or the other and sticking with it?
| Map is more general than mapcar, for example you could do the following rather than using mapcar:
(map 'list #'function listvar)
How do I keep scheme and CL separate in my head? I guess when you know both languages well enough you just know what works in one and not the other. Despite the syntactic similarities they are quite different languages in terms of style.
|
45,227 | 45,233 | List operations in Lisp | I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:
find the index of something in a list. example:
(index-of item InThisList)
replace something at a specific spot in a list. example:
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
return an item at a specific index. example:
(return InThisList ItemAtThisIndex)
Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.
This is how I've been faking number 1:
(defun my-index (findMe mylist)
(let ((counter 0) (found 1))
(dolist (item mylist)
(cond
((eq item findMe) ;this works because 'eq' checks place in memory,
;and as long as 'findMe' was from the original list, this will work.
(setq found nil)
(found (incf counter))))
counter))
| You can use setf and nth to replace and retrieve values by index.
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101); <----
myList)
(1 2 3 4 101 6)
To find by index you can use the position function.
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101)
(list myList (position 101 myList)))
((1 2 3 4 101 6) 4)
I found these all in this index of functions.
|
59,428 | 59,434 | Which environment, IDE or interpreter to put in practice Scheme? | I've been making my way through The Little Schemer and I was wondering what environment, IDE or interpreter would be best to use in order to test any of the Scheme code I jot down for myself.
| Racket (formerly Dr Scheme) has a nice editor, several different Scheme dialects, an attempt at visual debugging, lots of libraries, and can run on most platforms. It even has some modes specifically geared around learning the language.
|
60,260 | 60,267 | My first Lisp macro; is it leaky? | I've been working through Practical Common Lisp and as an exercise decided to write a macro to determine if a number is a multiple of another number:
(defmacro multp (value factor)
`(= (rem ,value ,factor) 0))
so that :
(multp 40 10)
evaluates to true whilst
(multp 40 13)
does not
The question is does this macro leak in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?
| Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both value and factor are evaluated only once and in order, and rem doesn't have any side effects.
This is not good Lisp though, because there's no reason to use a macro in this case. A function
(defun multp (value factor)
(zerop (rem value factor)))
is identical for all practical purposes. (Note the use of zerop. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, (= ... 0) might be better)
|
60,910 | 60,948 | Changing the font in Aquamacs? | I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change.
| This is what I have in my .emacs for OS X:
(set-default-font "-apple-bitstream vera sans mono-medium-r-normal--0-0-0-0-m-0-mac-roman")
Now, I'm not sure Bitstream Vera comes standard on OS X, so you may have to either download it or choose a different font. You can search the X font names by running (x-list-fonts "searchterm") in an ELisp buffer (e.g. *scratch* - to run it, type it in and then type C-j on the same line).
|
64,953 | 77,554 | Anyone using Lisp for a MySQL-backended web app? | I keep hearing that Lisp is a really productive language, and I'm enjoying SICP. Still, I'm missing something useful that would let me replace PHP for server-side database interaction in web applications.
Is there something like PHP's PDO library for Lisp or Arc or Scheme or one of the dialects?
| newLisp has support for mysql5 and if you look at the mysql5 function calls, you'll see that it's close to PDO.
|
65,607 | 65,641 | Writing a ++ macro in Common Lisp | I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons. I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not. My idea of how this would be defined would be
(defmacro ++ (variable)
(incf variable))
but this gives me a SIMPLE-TYPE-ERROR when trying to use it. What would make it work?
| Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote:
(defmacro ++ (variable)
`(incf ,variable))
|
66,542 | 1,685,449 | How do I run Oracle plsql procedure from Lisp? | How do I get started?
| I have found the easiest way to achieve this by using Clojure.
Here is the example code:
(ns example
(:require [clojure.contrib.sql :as sql])
(:import [java.sql Types]))
(def devdb {:classname "oracle.jdbc.driver.OracleDriver"
:subprotocol "oracle"
:subname "thin:username/password@localhost:1509:devdb"
:create true})
(defn exec-ora-stored-proc [input-param db callback]
(sql/with-connection db
(with-open [stmt (.prepareCall (sql/connection) "{call some_schema.some_package.test_proc(?, ?, ?)}")]
(doto stmt
(.setInt 1 input-param)
(.registerOutParameter 2 Types/INTEGER)
(.registerOutParameter 3 oracle.jdbc.driver.OracleTypes/CURSOR)
(.execute))
(callback (. stmt getInt 2) (. stmt getObject 3)))))
(exec-ora-stored-proc
123 ;;input param value
devdb
(fn [err-code res-cursor]
(println (str "ret_code: " err-code))
;; prints returned refcursor rows
(let [resultset (resultset-seq res-cursor)]
(doseq [rec resultset]
(println rec)))))
|
77,934 | 104,227 | How do I display an image with ltk? | I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?
| It has been a while since I used LTK for anything, but the simplest way to display an image with LTK is as follows:
(defpackage #:ltk-image-example
(:use #:cl #:ltk))
(in-package #:ltk-image-example)
(defun image-example ()
(with-ltk ()
(let ((image (make-image)))
(image-load image "testimage.gif")
(let ((canvas (make-instance 'canvas)))
(create-image canvas 0 0 :image image)
(configure canvas :width 800)
(configure canvas :height 640)
(pack canvas)))))
Unfortunately what you can do with the image by default is fairly limited, and you can only use gif or ppm images - but the ppm file format is very simple, you could easily create a ppm image from your bitmap. However you say you want to manipulate the displayed image, and looking at the code that defines the image object:
(defclass photo-image(tkobject)
((data :accessor data :initform nil :initarg :data)
)
)
(defmethod widget-path ((photo photo-image))
(name photo))
(defmethod initialize-instance :after ((p photo-image)
&key width height format grayscale data)
(check-type data (or null string))
(setf (name p) (create-name))
(format-wish "image create photo ~A~@[ -width ~a~]~@[ -height ~a~]~@[ -format \"~a\"~]~@[ -grayscale~*~]~@[ -data ~s~]"
(name p) width height format grayscale data))
(defun make-image ()
(let* ((name (create-name))
(i (make-instance 'photo-image :name name)))
;(create i)
i))
(defgeneric image-load (p filename))
(defmethod image-load((p photo-image) filename)
;(format t "loading file ~a~&" filename)
(send-wish (format nil "~A read {~A} -shrink" (name p) filename))
p)
It looks like the the actual data for the image is stored by the Tcl/Tk interpreter and not accessible from within lisp. If you wanted to access it you would probably need to write your own functions using format-wish and send-wish.
Of course you could simply render each pixel individually on a canvas object, but I don't think you would get very good performance doing that, the canvas widget gets a bit slow once you are trying to display more than a few thousand different things on it. So to summarize - if you don't care about doing anything in real time, you could save your bitmap as a .ppm image every time you wanted to display it and then simply load it using the code above - that would be the easiest. Otherwise you could try to access the data from tk itself (after loading it once as a ppm image), finally if none of that works you could switch to another toolkit. Most of the decent lisp GUI toolkits are for linux, so you may be out of luck if you are using windows.
|
94,792 | 101,194 | Using Vim for Lisp development | I've been using Lisp on and off for a while but I'm starting to get more serious about doing some "real" work in Lisp. I'm a huge Vim fan and was wondering how I can be most productive using Vim as my editor for Lisp development. Plugins, work flow suggestions, etc. are all welcome.
Please don't say "use emacs" as I've already ramped up on Vim and I'm really enjoying it as an editor.
| Limp aims to be a fully featured Common Lisp IDE for Vim. It defaults to SBCL, but can be changed to support most other implementations by replacing "sbcl" for your favourite lisp, in the file /usr/local/limp/latest/bin/lisp.sh
When discussing Lisp these days, it is commonly assumed to be Common Lisp, the language standardized by ANSI X3J13 (see the HyperSpec, and Practical Common Lisp for a good textbook) with implementations such as GNU Clisp, SBCL, CMUCL, AllegroCL, and many others.
Back to Limp. There are other solutions that are more light-weight, or try to do other things, but I believe in providing an environment that gives you things like bracket matching, highlighting, documentation lookup, i.e. making it a turn-key solution as much as possible.
In the Limp repository you'll find some of the previous work of the SlimVim project, namely the ECL (Embeddable Common Lisp) interface, merged with later releases (7.1); Simon has also made patches to 7.2 available yet to be merged. The ECL interface is documented in if_ecl.txt.
Short-term work is to do said merging with 7.2 and submit a patch to vim_dev to get it merged into the official Vim tree.
Which leads us to the long-term plans: having Lisp directly in Vim will make it convenient to start working on a SWANK front-end (the part of SLIME that runs in your Lisp, with slime.el being the part that runs in the editor - the frontend).
And somewhere in between, it is likely that all of Limp will be rewritten in Common Lisp using the ECL interface, making Limp easier to maintain (VimScript isn't my favourite) and being easier for users to customize.
The official Limp site goes down from time to time, but as pointed out, the download at Vim.org should always work, and the support groups limp-devel and limp-user are hosted with Google Groups. Don't hesitate to join if you feel you need a question answered, or perhaps even want to join in on development. Most of the discussion takes place on the limp-devel list. If you're into IRC, I'm in #limp on irc.freenode.net as 'tic'.
Good luck!
|
96,249 | 96,477 | How do I append to an alist in scheme? | Adding an element to the head of an alist (Associative list) is simple enough:
> (cons '(ding . 53) '((foo . 42) (bar . 27)))
((ding . 53) (foo . 42) (bar . 27))
Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this:
> (define (alist-append alist pair) `(,@alist ,pair))
> (alist-append '((foo . 42) (bar . 27)) '(ding . 53))
'((foo . 42) (bar . 27) (ding . 53))
However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?
| You don't append to an a-list. You cons onto an a-list.
An a-list is logically a set of associations. You don't care about the order of elements in a set. All you care about is presence or absence of a particular element. In the case of an a-list, all you care about is whether there exists an association for a given tag (i.e., a pair whose CAR is the specified value), and, given that association, the associated value (i.e., in this implementation, the CDR of the pair).
|
100,048 | 100,109 | I need to join two lists, sort them and remove duplicates. Is there a better way to do this? | I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.
The elements can occur multiple times in both lists and they are originally unsorted.
My function looks like this:
(defun merge-lists (list-a list-b sort-fn)
"Merges two lists of (x, y) coordinates sorting them and removing dupes"
(let ((prev nil))
(remove-if
(lambda (point)
(let ((ret-val (equal point prev)))
(setf prev point)
ret-val))
(sort
(merge 'list list-a list-b sort-fn) ;'
sort-fn))))
Is there a better way to achieve the same?
Sample call:
[CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>)
==> (9 8 7 6 4 3 2 1)
| Our neighbourhood friendly Lisp guru pointed out the remove-duplicates function.
He also provided the following snippet:
(defun merge-lists (list-a list-b sort-fn test-fn)
(sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))
|
101,487 | 101,504 | Is it correct to use the backtick / comma idiom inside a (loop ...)? | I have some code which collects points (consed integers) from a loop which looks something like this:
(loop
for x from 1 to 100
for y from 100 downto 1
collect `(,x . ,y))
My question is, is it correct to use `(,x . ,y) in this situation?
Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.
| It would be much 'better' to just do (cons x y).
But to answer the question, there is nothing wrong with doing that :) (except making it a tad slower).
|
105,816 | 105,990 | How do I access a char ** through ffi in plt-scheme? | I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char ** (array of strings). If I declare my function as (_fun _pointer -> _pointer), how do I convert the result to a list of strings in scheme?
Here are the relevant C-declarations:
typedef char **MYSQL_ROW; /* return data as array of strings */
// ...
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
| I think that what you want is the cvector:
http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)
A cvector of _string/utf-8 or whichever encoding you need seems reasanable.
But that's from a quick survey of the docs - I haven't tried this myself. Please let me know if it works!
|
106,597 | 107,649 | Why are fixnums in Emacs only 29 bits? | And why don't they change it?
Edit:
The reason ask is because I'm new to emacs and I would like to use Emacs as a "programmer calculator". So, I can manipulate 32-bit & 64-bit integers and have them behave as they would on the native machine.
| Emacs-Lisp is a dynamically-typed language. This means that you need type tags at runtime. If you wanted to work with numbers, you would therefore normally have to pack them into some kind of tagged container that you can point to (i.e. “box” them), as there is no way of distinguishing a pointer from a machine integer at runtime without some kind of tagging scheme.
For efficiency reasons, most Lisp implementations do therefore not use raw pointers but what I think is called descriptors. These descriptors are usually a single machine word that may represent a pointer, an unboxed number (a so-called fixnum), or one of various other hard-coded data structures (it's often worth encoding NIL and cons cells specially, too, for example).
Now, obviously, if you add the type tag, you don't have the full 32 bits left for the number, so you're left with 26 bits as in MIT Scheme or 29 bits as in Emacs or any other number of bits that you didn't use up for tagging.
Some implementations of various dynamic languages reserve multiple tags for fixnums so that they can give you 30-bit or even 31-bit fixnums. SBCL is one implementation of Common Lisp that does this. I don't think the complication that this causes is worth it for Emacs, though. How often do you need fast 30-bit fixnum arithmetic as opposed to 29-bit fixnum arithmetic in a text editor that doesn't even compile its Lisp code into machine code (or does it? I don't remember, actually)? Are you writing a distributed.net client in Emacs-Lisp? Better switch to Common Lisp, then! ;)
|
108,081 | 108,142 | Are there any High Level, easy to install GUI libraries for Common Lisp? | Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?
| Ltk is quite popular, very portable, and reasonably well documented through the Tk docs. Installation on SBCL is as easy as saying:
(require :asdf-install)
(asdf-install:install :ltk)
There's also Cells-Gtk, which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells.
EDIT: Note that ASDF-INSTALL is integrated this well with SBCL only. Installing libraries from within other Lisp implementations may prove harder. (Personally, I always install my libraries from within SBCL and then use them from all implementations.) Sorry about any confusion this may have caused.
|
108,169 | 108,248 | How do I take a slice of a list (A sublist) in scheme? | Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?
EDIT:
Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.
| The following code will do what you want:
(define get-n-items
(lambda (lst num)
(if (> num 0)
(cons (car lst) (get-n-items (cdr lst) (- num 1)))
'()))) ;'
(define slice
(lambda (lst start count)
(if (> start 1)
(slice (cdr lst) (- start 1) count)
(get-n-items lst count))))
Example:
> (define l '(2 3 4 5 6 7 8 9)) ;'
()
> l
(2 3 4 5 6 7 8 9)
> (slice l 2 4)
(3 4 5 6)
>
|
108,537 | 108,619 | What are the main differences between CLTL2 and ANSI CL? | Any online links / resources?
| Bill Clementson has http://bc.tech.coop/cltl2-ansi.htm which is a repost of http://groups.google.com/group/comp.lang.lisp/msg/0e9aced3bf023d86
I also found http://web.archive.org/web/20060111013153/http://www.ntlug.org/~cbbrowne/commonlisp.html#AEN10329 while answering the question. I've not compared the two.
As the posters note, those are only main differences. The intent is to let you tweak your copy of cltl2 into not confusing you in any major way, but the resulting document should not be treated as standard.
Personally I didn't bother-- I use cltl2 as a bed side reading (Steele is an excellent writer!), to gain insight into various aspects of the language, and the process by which those aspects were standardized; lets me think in CL better. When I program, I reference HyperSpec exclusively.
|
108,940 | 269,758 | How do I use (require :PACKAGE) in clisp under Ubuntu Hardy? | I am trying to evaluate the answer provided here, and am getting the error: "A file with name ASDF-INSTALL does not exist" when using clisp:
dsm@localhost:~$ clisp -q
[1]> (require :asdf-install)
*** - LOAD: A file with name ASDF-INSTALL does not exist
The following restarts are available:
ABORT :R1 ABORT
Break 1 [2]> :r1
[3]> (quit)
dsm@localhost:~$
cmucl throws a similar error:
dsm@localhost:~$ cmucl -q
Warning: #<Command Line Switch "q"> is an illegal switch
CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile
With core: /usr/lib/cmucl/lisp.core
Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost
For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS.
or to [email protected]
type (help) for help, (quit) to exit, and (demo) to see the demos
Loaded subsystems:
Python 1.1, target Intel x86
CLOS based on Gerd's PCL 2004/04/14 03:32:47
* (require :asdf-install)
Error in function REQUIRE: Don't know how to load ASDF-INSTALL
[Condition of type SIMPLE-ERROR]
Restarts:
0: [ABORT] Return to Top-Level.
Debug (type H for help)
(REQUIRE :ASDF-INSTALL NIL)
Source:
; File: target:code/module.lisp
(ERROR "Don't know how to load ~A" MODULE-NAME)
0] (quit)
dsm@localhost:~$
But sbcl works perfectly:
dsm@localhost:~$ sbcl -q
This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (require :asdf-install)
; loading system definition from
; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #<PACKAGE "ASDF0">
; registering #<SYSTEM SB-BSD-SOCKETS {AB01A89}> as SB-BSD-SOCKETS
; registering #<SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}> as SB-BSD-SOCKETS-TESTS
("SB-BSD-SOCKETS" "ASDF-INSTALL")
* (quit)
Any ideas on how to fix this? I found this post on the internet, but using that didn't work either.
| use clc:clc-require in clisp. Refer to 'man common-lisp-controller'. I had the same error in clisp and resolved it by using clc:clc-require. sbcl works fine with just require though.
|
110,433 | 115,898 | Are there any Common Lisp implementations for .Net? | Are there any Common Lisp implementations for .Net?
| I haven't looked at it recently, but at least in the past there were some problems with fully implementing common lisp on the CLR, and I'd be a little surprised if this has changed. The issues come up with things like the handling of floats where .net/clr has a way to do it that is a) subtly incorrect b) disagrees with the ANSI standard for common lisp but c) doesn't allow any way around this. There are other similar problems. This stuff is fiddly and perhaps not too important, but means you are unlikely to see an ANSI CL on the CLR.
There are bigger issues, for example common lisp has a more powerful object system, so you can't map it 1:1 to object in the runtime (no MI, for one). This is ok, but leaves you with an inside/outside sort of approach which is what a common runtime tries to avoid...
Whether or not you'll see a common lisp-ish variant running on it is a different story, but I don't know of any at the moment (not that I've looked hard)
|
110,911 | 129,009 | What is the closest thing to Slime for Scheme? | I do most of my development in Common Lisp, but there are some moments when I want to switch to Scheme (while reading Lisp in Small Pieces, when I want to play with continuations, or when I want to do some scripting in Gauche, for example). In such situations, my main source of discomfort is that I don't have Slime (yes, you may call me an addict).
What is Scheme's closest counterpart to Slime? Specifically, I am most interested in:
Emacs integration (this point is obvious ;))
Decent tab completion (ideally, c-w-c-c TAB should expand to call-with-current-continuation). It may be even symbol-table based (ie. it doesn't have to notice a function I defined in a let at once).
Function argument hints in the minibuffer (if I have typed (map |) (cursor position is indicated by |)), I'd like to see (map predicate . lists) in the minibuffer
Sending forms to the interpreter
Integration with a debugger.
I have ordered the features by descending importance.
My Scheme implementations of choice are:
MzScheme
Ikarus
Gauche
Bigloo
Chicken
It would be great if it worked at least with them.
| You also might consider Scheme Complete:
http://www.emacswiki.org/cgi-bin/wiki/SchemeComplete
It basically provides tab-completion.
|
116,654 | 116,661 | Non-C++ languages for generative programming? | C++ is probably the most popular language for static metaprogramming and Java doesn't support it.
Are there any other languages besides C++ that support generative programming (programs that create programs)?
| The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading Paul Graham's On Lisp and also taking a look at Clojure if you're interested in a Lisp with macros that runs on the JVM.
Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming.
|
123,234 | 123,410 | What is the best SQL library for use in Common Lisp? | Ideally something that will work with Oracle, MS SQL Server, MySQL and Posgress.
| if you mean common lisp by lisp, then there's cl-rdbms. it is heavily tested on postgres (uses postmodern as the backend lib), it has a toy sqlite backend and it also has an OCI based oracle backend. it supports abstracting away the different sql dialects, has an sql quasi-quote syntax extension installable on e.g. the [] characters.
i'm not sure if it's the best, and i'm biased anyway... :) but we ended up rolling our own lib after using clsql for a while, which is i think the most widely used sql lib for cl.
see cliki page about sql for a further reference.
|
126,790 | 129,402 | If you already know LISP, why would you also want to learn F#? | What is the added value for learning F# when you are already familiar with LISP?
|
Static typing (with type inference)
Algebraic data types
Pattern matching
Extensible pattern matching with active patterns.
Currying (with a nice syntax)
Monadic programming, called 'workflows', provides a nice way to do asynchronous programming.
A lot of these are relatively recent developments in the programming language world. This is something you'll see in F# that you won't in Lisp, especially Common Lisp, because the F# standard is still under development. As a result, you'll find there is a quite a bit to learn. Of course things like ADTs, pattern matching, monads and currying can be built as a library in Lisp, but it's nicer to learn how to use them in a language where they are conveniently built-in.
The biggest advantage of learning F# for real-world use is its integration with .NET.
|
130,475 | 131,334 | Why is Lisp used for AI? | I've been learning Lisp to expand my horizons because I have heard that it is used in AI programming. After doing some exploring, I have yet to find AI examples or anything in the language that would make it more inclined towards it.
Was Lisp used in the past because it was available, or is there something that I'm just missing?
| Lisp WAS used in AI until the end of the 1980s. In the 80s, though, Common Lisp was oversold to the business world as the "AI language"; the backlash forced most AI programmers to C++ for a few years. These days, prototypes usually are written in a younger dynamic language (Perl, Python, Ruby, etc) and implementations of successful research is usually in C or C++ (sometimes Java).
If you're curious about the 70's...well, I wasn't there. But I think Lisp was successful in AI research for three reasons (in order of importance):
Lisp is an excellent prototyping tool. It was the best for a very long time. Lisp is still great at tackling a problem you don't know how to solve yet. That description characterises AI perfectly.
Lisp supports symbolic programming well. Old AI was also symbolic. It was also unique in this regard for a long time.
Lisp is very powerful. The code/data distinction is weaker so it feels more extensible than other languages because your functions and macros look like the built-in stuff.
I do not have Peter Norvig's old AI book, but it is supposed to be a good way to learn to program AI algorithms in Lisp.
Disclaimer: I am a grad student in computational linguistics. I know the subfield of natural language processing a lot better than the other fields. Maybe Lisp is used more in other subfields.
|
130,636 | 130,752 | How to compile Clisp 2.46? | When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure:
Configure findings:
FFI: no (user requested: default)
readline: yes (user requested: yes)
libsigsegv: no, consider installing GNU libsigsegv
./configure: libsigsegv was not detected, thus some features, such as
generational garbage collection and
stack overflow detection in interpreted Lisp code
cannot be provided.
Please do this:
mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu
wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz
tar xfz libsigsegv-2.5.tar.gz
cd libsigsegv-2.5
./configure --prefix=${prefix} && make && make check && make install
cd ../..
./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp
If you insist on building without libsigsegv, please pass
--ignore-absence-of-libsigsegv
to this script:
./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp
I've tried doing as requested, but it didn't help: it seems to ignore the --with-libsigsegv-prefix option. I also tried putting installing libsigsegv in a standard location (/usr/local). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system.
I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).
| Here are my notes from compiling CLISP on Ubuntu in the past, hope this helps:
sudo apt-get install libsigsegv-dev libreadline5-dev
# as of 7.10, Ubuntu's libffcall1-dev is broken and I had to get it from CVS
# and make sure CLISP didn't use Ubuntu's version.
sudo apt-get remove libffcall1-dev libffcall1
cvs -z3 -d:pserver:[email protected]:/sources/libffcall co -P ffcall
cd ffcall; ./configure; make
sudo make install
cvs -z3 -d:pserver:[email protected]:/cvsroot/clisp co -P clisp
cd clisp
./configure --with-libffcall-prefix=/usr/local --prefix=/home/luis/Software
ulimit -s 16384
cd src; make install
|
131,023 | 131,246 | List Comprehension Library for Scheme? | I know there is a list-comprehension library for common lisp (incf-cl), I know they're supported natively in various other functional (and some non-functional) languages (F#, Erlang, Haskell and C#) - is there a list comprehension library for Scheme?
incf-cl is implemented in CL as a library using macros - shouldn't it be possible to use the same techniques to create one for Scheme?
|
Swindle is primarily a CLOS emulator library, but it has list comprehensions too. I've used them, they're convenient, but the version I used was buggy and incomplete. (I just needed generic functions.)
However, you probably want SRFI-42. I haven't used it, but it HAS to have fewer bugs than the Swindle list comprehensions.
I don't know which Scheme you use. PLT Scheme bundles Swindle and SRFI-42. Both are supposed to be cross-Scheme compatible, though.
If you use PLT Scheme, here is SRFI-42's man page. You say (require srfi/42) to get it.
|
131,433 | 133,356 | Sources for learning about Scheme Macros: define-syntax and syntax-rules | I've read JRM's Syntax-rules Primer for the Merely Eccentric and it has helped me understand syntax-rules and how it's different from common-lisp's define-macro. syntax-rules is only one way of implementing a syntax transformer within define-syntax.
I'm looking for two things, the first is more examples and explanations of syntax-rules and the second is good sources for learning the other ways of using define-syntax. What resources do you recommend?
| To answer your second question: syntax-case is the other form that goes inside define-syntax. Kent Dybvig is the primary proponent of syntax-case, and he has a tutorial on using it [PDF].
I also read the PLT Scheme documentation on syntax-case for a few more examples, and to learn about the variation in implementation.
|
138,056 | 138,357 | When editing Lisp code, can emacs be configured to display each nested level of parentheses in a different color? | In other words, a block of code like this:
(setq initial-major-mode
(lambda ()
(text-mode)
(font-lock-mode)
))
... would come out looking like something like this:
If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it?
| I think you are looking for something like mwe-color-box.el
|
144,661 | 144,864 | Python vs. Ruby for metaprogramming | I'm currently primarily a D programmer and am looking to add another language to my toolbox, preferably one that supports the metaprogramming hacks that just can't be done in a statically compiled language like D.
I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. I don't want to start a language flame war, and I'm sure both Ruby and Python have their tradeoffs, so I'll list what's important to me personally. Please tell me whether Ruby, Python, or some other language would be best for me.
Important:
Good metaprogramming. Ability to create classes, methods, functions, etc. at runtime. Preferably, minimal distinction between code and data, Lisp style.
Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language.
Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project.
An interesting language that actually affects the way one thinks about programming.
Somewhat important:
Performance. It would be nice if performance was decent, but when performance is a real priority, I'll use D instead.
Well-documented.
Not important:
Community size, library availability, etc. None of these are characteristics of the language itself, and all can change very quickly.
Job availability. I am not a full-time, professional programmer. I am a grad student and programming is tangentially relevant to my research.
Any features that are primarily designed with very large projects worked on by a million code monkeys in mind.
| There's not really a huge difference between python and ruby at least at an ideological level. For the most part, they're just different flavors of the same thing. Thus, I would recommend seeing which one matches your programming style more.
|
145,699 | 145,731 | Combining Lisp and PHP code in the same application | At the moment I use PHP for almost everything I develop for the Web but its linguistic limitations are starting to annoy me. However, as I developed some practices and maintain some PHP libraries that help me a lot, I don't feel I'd be ready to just switch to LISP throwing away all my PHP output. It could even be impossible on the servers where all I have access to is a regular LAMP hosting account.
Ergo, my questions are:
Could LISP code be just combined with PHP one? Are there solutions for side-by-side LISP/PHP, interface for their interoperability or perphaps just an implementation of one for the other? Or is it a mutually exclusive choice?
| It's not a mutually-exclusive choice, you can run both on one system, in the same way that perl and php (for example) are run side-by-side on many systems.
There's a good post here on a similar topic, which suggests using sockets to communicate between both languages -
If you want to go the PHP<->Lisp route the easyest thing to do would be to make PHP communicate with your Lisp-process using sockets.
http://php.net/manual/en/ref.sockets.php
http://www.sbcl.org/manual/Networking.html
This approach does still leave you with the potential added complexity and maintenance issues you get from having 2 languages in your project, but might be a fit for your particular use case.
|
146,081 | 146,191 | Emacs: How do you store the last parameter supplied by the user as the default? | I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default.
(defun run-rake (param)
(interactive "sTask: ")
(shell-command (format "rake %s" task)))
The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.
I can't seem to find this in the documentation - how do you do this in elisp?
| You can see how the compile command does this. Bring up the help text for the compile command with C-h f compile, move the cursor over the name of the file that contains the function, then hit RETURN. This will bring up the source file for compile.
Basically, there's a dynamic/global variable compile-command that holds the last compile command. Emacs is a single-user, single-threaded system, so there's really no need for much more. Also keep in mind that Elisp is a very old school Lisp, and variables have dynamic (call stack), not lexical, scope. In this kind of system it is natural to:
(let ((compile-command "gcc -o foo foo.c frobnicate.c"))
...
(compile)
...)
Speaking of the compile command, have you tried using it instead of your own run-rake function?
|
147,918 | 148,139 | SBCL on Vista crashes. Do you know how to make it work? | I've searched a lot for an answer for this question in the web: they say it's true, SBCL doesn't work under Vista.
But I really need to work with lisp on my home Vista laptop and VM doesn't help really...
And CL is not so interesting because of speed...
If you have any recommendation, please share!
| Have you seen these articles?
http://robert.zubek.net/blog/2008/04/09/sbcl-emacs-windows-vista/
http://brainrack.wordpress.com/2008/05/29/running-sbcl-on-windows/
|
172,798 | 173,676 | Lisp in the real world | I have experimented with Lisp (actually Scheme) and found it to be a very beautiful language that I am interested in learning more about. However, it appears that Lisp is never used in serious projects, and I haven't seen it listed as a desired skill on any job posting. I am interested in hearing from anyone who has used Lisp or seen it used in the "real world", or who knows whether it is considered a purely academic language.
| Franz, Inc. provides an inexhaustive list of success stories on their website. However:
Please don't assume Lisp is only
useful for Animation and Graphics, AI,
Bioinformatics, B2B and E-Commerce,
Data Mining, EDA/Semiconductor
applications, Expert Systems, Finance,
Intelligent Agents, Knowledge
Management, Mechanical CAD, Modeling
and Simulation, Natural Language,
Optimization, Research, Risk Analysis,
Scheduling, Telecom, and Web Authoring
just because these are the only things
they happened to list. — Kent Pitman
We can find other success stories here: http://lisp-lang.org/success/
and a list of current companies using Common Lisp: https://github.com/azzamsa/awesome-lisp-companies
|
187,219 | 187,393 | How do I get a terminal program to honour cursor keys? | I'm using ccl/openmcl on Mac OS X. (latest versions of both). When the lisp prompt is displayed, using the cursor keys to navigate the current line results in escape codes, rather than movement, eg:
Welcome to Clozure Common Lisp Version 1.2-r9226-RC1 (DarwinX8664)!
? (^[[D
Here I've pressed the ( key, and then the left cursor key.
When I run ccl/openmcl on a Debian Etch box, the cursor behaves as expected, and moves the insert point one position left.
I guess this is some sort of terminal configuration option?
| If Clozure CL doesn't provide native readline/editline/whatever support or is configured not to use it, you can run it with rlwrap, for example:
rlwrap openmcl
rlwrap can be obtained via MacPorts or directly from http://utopia.knoware.nl/~hlub/rlwrap/.
|
192,049 | 192,336 | Is it possible to have an alias for the function name in Lisp? | ...just like packages do.
I use Emacs (maybe, it can offer some kind of solution).
For example (defun the-very-very-long-but-good-name () ...) is not to useful later in code. But the name like Fn-15 or the first letters abbreviation is not useful too.
Is it possible either to have an alias like for packages or to access the documentation string while trying to recall the function's name?
In other words, is it possible for functions to mix somehow self-documenting and short names?
| You want defalias. (defalias 'newname 'oldname) will preserve documentation and even show "newname is an alias for `oldname'" when its documentation is requested.
|
192,602 | 192,972 | Are there documented, organized collections of libraries for Common Lisp? | I am a college student at a school that teaches mainly in Java. One of the strong points of Java, which I quite enjoy, is the large collection of libraries. What makes these libraries especially useful is the extensive documentation and organization presented via JavaDoc. Are there any library collections for Common Lisp which also have these qualities, and is there a tool similar to JavaDoc which would assist in the building, maintaining, or expanding of these libraries?
| No, there is no comprehensive, consistently documented library collection. The inexistence of such a thing is Common Lisp's biggest problem right now. If you're interested in helping the Lisp community, this may well be the thing to attack first.
Also, while there are various JavaDoc equivalents, there is no widely accepted quasi-standard as for Java.
|
208,835 | 208,940 | Function pointers, Closures, and Lambda | I am just now learning about function pointers and, as I was reading the K&R chapter on the subject, the first thing that hit me was, "Hey, this is kinda like a closure." I knew this assumption is fundamentally wrong somehow and after a search online I didn't find really any analysis of this comparison.
So why are C-style function pointers fundamentally different from closures or lambdas? As far as I can tell it has to do with the fact that the function pointer still points to a defined (named) function as opposed to the practice of anonymously defining the function.
Why is passing a function to a function seen as more powerful in the second case, where it is unnamed, than the first where it is just a normal, everyday function that is being passed?
Please tell me how and why I am wrong to compare the two so closely.
| A lambda (or closure) encapsulates both the function pointer and variables. This is why, in C#, you can do:
int lessThan = 100;
Func<int, bool> lessThanTest = delegate(int i) {
return i < lessThan;
};
I used an anonymous delegate there as a closure (it's syntax is a little clearer and closer to C than the lambda equivalent), which captured lessThan (a stack variable) into the closure. When the closure is evaluated, lessThan (whose stack frame may have been destroyed) will continue to be referenced. If I change lessThan, then I change the comparison:
int lessThan = 100;
Func<int, bool> lessThanTest = delegate(int i) {
return i < lessThan;
};
lessThanTest(99); // returns true
lessThan = 10;
lessThanTest(99); // returns false
In C, this would be illegal:
BOOL (*lessThanTest)(int);
int lessThan = 100;
lessThanTest = &LessThan;
BOOL LessThan(int i) {
return i < lessThan; // compile error - lessThan is not in scope
}
though I could define a function pointer that takes 2 arguments:
int lessThan = 100;
BOOL (*lessThanTest)(int, int);
lessThanTest = &LessThan;
lessThanTest(99, lessThan); // returns true
lessThan = 10;
lessThanTest(100, lessThan); // returns false
BOOL LessThan(int i, int lessThan) {
return i < lessThan;
}
But, now I have to pass the 2 arguments when I evaluate it. If I wished to pass this function pointer to another function where lessThan was not in scope, I would either have to manually keep it alive by passing it to each function in the chain, or by promoting it to a global.
Though most mainstream languages that support closures use anonymous functions, there is no requirement for that. You can have closures without anonymous functions, and anonymous functions without closures.
Summary: a closure is a combination of function pointer + captured variables.
|
213,538 | 213,566 | centering text in common lisp | I have a string that I would like to print . Is it possible to center it when printing ?
| Use the ~< formatting directive. This will return "hello there" centered within 70 columns.
(format nil "~70:@<~A~>" "hello there")
|
215,883 | 614,707 | Creating a lambda from an s-expression | I have an s-expression bound to a variable in Common Lisp:
(defvar x '(+ a 2))
Now I want to create a function that when called, evaluates the expression in the scope in which it was defined. I've tried this:
(let ((a 4))
(lambda () (eval x)))
and
(let ((a 4))
(eval `(lambda () ,x)))
But both of these create a problem: EVAL will evaluate the code at the top level, so I can't capture variables contained in the expression. Note that I cannot put the LET form in the EVAL. Is there any solution?
EDIT: So if there is not solution to the EVAL problem, how else can it be done?
EDIT: There was a question about what exactly I am try to do. I am writing a compiler. I want to accept an s-expression with variables closed in the lexical environment where the expression is defined. It may indeed be better to write it as a macro.
| You need to create code that has the necessary bindings. Wrap a LET around your code and bind every variable you want to make available in your code:
(defvar *x* '(+ a 2))
(let ((a 4))
(eval `(let ((a ,a))
,*x*)))
|
223,468 | 223,484 | Can someone help explain this scheme procedure | Question:
((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))
This was #1 on the midterm, I put "81 9" he thought I forgot to cross one out lawl, so I cross out 81, and he goes aww. Anyways, I dont understand why it's 81.
I understand why (lambda (x) (* x x)) (* 3 3) = 81, but the first lambda I dont understand what the x and y values are there, and what the [body] (x y) does.
So I was hoping someone could explain to me why the first part doesn't seem like it does anything.
| This needs some indentation to clarify
((lambda (x y) (x y))
(lambda (x) (* x x))
(* 3 3))
(lambda (x y) (x y)); call x with y as only parameter.
(lambda (x) (* x x)); evaluate to the square of its parameter.
(* 3 3); evaluate to 9
So the whole thing means: "call the square function with the 9 as parameter".
EDIT: The same thing could be written as
((lambda (x) (* x x))
(* 3 3))
I guess the intent of the exercise is to highlight how evaluating a scheme form involves an implicit function application.
|
231,649 | 232,638 | Lisp introspection? when a function is called and when it exits | With common lisp and I am assuming the introspection properties. How can I add code to common lisp code that will tell me when a function is called and when has finished executing. I want to take any lisp code and this particular modification to the code. I figure with lisp's AST analysis, this should be possible.
| You can use (trace function) for a simple mechanism. For something more involved, here is a good discussion from comp.lang.lisp.
[CL_USER]>
(defun fac (n)
"Naïve factorial implementation"
(if (< 1 n)
(* n (fac (- n 1)))
1))
FAC
[CL_USER]> (trace fac)
;; Tracing function FAC.
(FAC)
[CL_USER]> (fac 5)
1. Trace: (FAC '5)
2. Trace: (FAC '4)
3. Trace: (FAC '3)
4. Trace: (FAC '2)
5. Trace: (FAC '1)
5. Trace: FAC ==> 1
4. Trace: FAC ==> 2
3. Trace: FAC ==> 6
2. Trace: FAC ==> 24
1. Trace: FAC ==> 120
120
[CL_USER]>
|
232,486 | 234,842 | Best Common Lisp IDE | I've used Slime within Emacs as my primary development environment for Common Lisp (or Aquamacs on OS X), but are there other compelling choices out there? I've heard about Lispworks, but is that [or something else] worth looking at? Or does anyone have tips to getting the most out of Emacs (e.g., hooking it up to the hyperspec for easy reference)?
Update: Section 7 of Pascal Costanza's Highly Opinionated Guide to Lisp give one perspective. But to me, SLIME really seems to be where it's at.
More resources:
Video of Marco Baringer showing SLIME
Videos of Sven Van Caekenberghe showing the LispWorks IDE
Video of Rainer Joswig using the LispWorks IDE to create a DSL
Blog post by Bill Clementson discussing IDE choices
| There are some flashier options out there, but I don't think anything's better than Emacs and SLIME. I'd stick with what you're using and just work on pimping your Emacs install.
|
233,171 | 5,944,667 | What is the best way to do GUIs in Clojure? | What is the best way to do GUIs in Clojure?
Is there an example of some functional Swing or SWT wrapper?
Or some integration with JavaFX declarative GUI description which could be easily wrapped to s-expressions using some macrology?
Any tutorials?
| I will humbly suggest Seesaw.
Here's a REPL-based tutorial that assumes no Java or Swing knowledge.
Seesaw's a lot like what @tomjen suggests. Here's "Hello, World":
(use 'seesaw.core)
(-> (frame :title "Hello"
:content "Hello, Seesaw"
:on-close :exit)
pack!
show!)
and here's @Abhijith and @dsm's example, translated pretty literally:
(ns seesaw-test.core
(:use seesaw.core))
(defn handler
[event]
(alert event
(str "<html>Hello from <b>Clojure</b>. Button "
(.getActionCommand event) " clicked.")))
(-> (frame :title "Hello Swing" :on-close :exit
:content (button :text "Click Me" :listen [:action handler]))
pack!
show!)
|
238,174 | 243,288 | Cross-compiling with SBCL | I have SBCL running on a Ubuntu machine. I want to write a little program that I want to give to a friend who has only Windows running. What is the quickest way to cross-compile it on my machine into a "standalone" windows program (i.e. the usual runtime+core combination)?
| SBCL is able to do a cross-compilation, but due to code being evaluated during the process, you need access to the target architecture. SBCL's build processed is well explained by Christophe Rhodes in SBCL: a Sanely-Bootstrappable Common Lisp
.
If you don't have directly access to a Windows machine, I suppose you could give a try to Wine (I would expect this to fail) or ReactOS inside either an emulator or hypervisor (QEMU, HVM, Xen, you name it...).
|
245,677 | 247,229 | What are some things that you've used Scheme macros for? | Many examples of macros seem to be about hiding lambdas, e.g. with-open-file in CL. I'm looking for some more exotic uses of macros, particularly in PLT Scheme. I'd like to get a feel for when to consider using a macro vs. using functions.
| I only use Scheme macros (define-syntax) for tiny things like better lambda syntax:
(define-syntax [: x]
(syntax-case x ()
([src-: e es ...]
(syntax-case (datum->syntax-object #'src-: '_) ()
(_ #'(lambda (_) (e es ...)))))))
Which lets you write
[: / _ 2] ; <-- much better than (lambda (x) (/ x 2))
Dan Friedman has a mind-bending implementation of OO using macros: http://www.cs.indiana.edu/~dfried/ooo.pdf
But honestly, all the useful macros I've defined are stolen from Paul Graham's On Lisp and are generally easier to write with defmacro (define-macro in PLT Scheme). For example, aif is pretty ugly with define-syntax.
(define-syntax (aif x)
(syntax-case x ()
[(src-aif test then else)
(syntax-case (datum->syntax-object (syntax src-aif) '_) ()
[_ (syntax (let ([_ test]) (if (and _ (not (null? _))) then else)))])]))
define-syntax is odd in that it's only easy to use for very simple macros, where you are glad of the inability to capture variables; and very complicated macro DSLs, where you are glad of the inability to capture variables easily. In the first case you want to write the code without thinking about it, and in the second case you have thought enough about the DSL that you are willing to write part of it in the syntax-rules/syntax-case language which is not Scheme in order to avoid mystifying bugs.
But I don't use macros that much in Scheme. Idiomatic Scheme is so functional that many times you just want to write a functional program and then hide a few lambdas. I got on the functional train and now believe that if you have a lazy language or a good syntax for lambda, even that isn't necessary, so macros are not all that useful in a purely functional style.
So I'd recommend Practical Common Lisp and On Lisp. If you want to use PLT Scheme, I think most of their defmacro macros will work with define-macro. Or just use Common Lisp.
|
248,180 | 248,385 | Lisp DO variable syntax reasoning | In Peter Seibel's Practical Common Lisp, he gives this example:
(do ((nums nil) (i 1 (1+ i)))
((> i 10) (nreverse nums))
(push i nums))
I can see how it works, using nums inside the loop but not giving it a step-form. Why would you put nums in the variable-definition rather than do this:
(let (nums) (do ((i 1 (+ i 1)))
((> i 10) (nreverse nums))
(push i nums)))
I'm sure there's a good reason, but I don't get it yet.
| Because it's convenient and saves indentation. Furthermore, the accumulator conceptually belongs to the loop, so why not put it there?
|
256,507 | 257,224 | How do I memoize a recursive function in Lisp? | I'm a Lisp beginner. I'm trying to memoize a recursive function for calculating the number of terms in a Collatz sequence (for problem 14 in Project Euler). My code as of yet is:
(defun collatz-steps (n)
(if (= 1 n) 0
(if (evenp n)
(1+ (collatz-steps (/ n 2)))
(1+ (collatz-steps (1+ (* 3 n)))))))
(defun p14 ()
(defvar m-collatz-steps (memoize #'collatz-steps))
(let
((maxsteps (funcall m-collatz-steps 2))
(n 2)
(steps))
(loop for i from 1 to 1000000
do
(setq steps (funcall m-collatz-steps i))
(cond
((> steps maxsteps)
(setq maxsteps steps)
(setq n i))
(t ())))
n))
(defun memoize (fn)
(let ((cache (make-hash-table :test #'equal)))
#'(lambda (&rest args)
(multiple-value-bind
(result exists)
(gethash args cache)
(if exists
result
(setf (gethash args cache)
(apply fn args)))))))
The memoize function is the same as the one given in the On Lisp book.
This code doesn't actually give any speedup compared to the non-memoized version. I believe it's due to the recursive calls calling the non-memoized version of the function, which sort of defeats the purpose. In that case, what is the correct way to do the memoization here? Is there any way to have all calls to the original function call the memoized version itself, removing the need for the special m-collatz-steps symbol?
EDIT: Corrected the code to have
(defvar m-collatz-steps (memoize #'collatz-steps))
which is what I had in my code.
Before the edit I had erroneously put:
(defvar collatz-steps (memoize #'collatz-steps))
Seeing that error gave me another idea, and I tried using this last defvar itself and changing the recursive calls to
(1+ (funcall collatz-steps (/ n 2)))
(1+ (funcall collatz-steps (1+ (* 3 n))))
This does seem to perform the memoization (speedup from about 60 seconds to 1.5 seconds), but requires changing the original function. Is there a cleaner solution which doesn't involve changing the original function?
| I assume you're using Common-Lisp, which has separate namespaces for variable and function names. In order to memoize the function named by a symbol, you need to change its function binding, through the accessor `fdefinition':
(setf (fdefinition 'collatz-steps) (memoize #'collatz-steps))
(defun p14 ()
(let ((mx 0) (my 0))
(loop for x from 1 to 1000000
for y = (collatz-steps x)
when (< my y) do (setf my y mx x))
mx))
|
260,685 | 260,705 | What is the best Scheme implementation for working through SICP? | I have been using PLT Scheme, but it has some issues. Does anyone know of a better implementation for working through SICP?
| Use MIT Scheme.
It's recommended by the authors of SICP, and is used at MIT for the 6.001: Structure and Interpretation of Computer Programs course.
|
262,628 | 262,684 | Using Lisp (or AutoLisp) how good is the associative lists performance? | I'm doing an AutoLisp project which uses long associative structures to do heavy geometrical processing - so I'm curious about the associative list intense use timing results.
How simple/complex is the implementation? It uses some data structure or a normal list of dotted pairs?
The are any extension for b-tree or something?
| In Common Lisp and Emacs Lisp association lists are linked lists, so they have linear search time. Assuming that AutoLisp is the same (and if it isn't, then their use of the term "Associative List" is misleading), you can assume that all operations will be linear in the length of the list. For example, an alist with 100 elements will, on average, need 50 accesses to find the thing that you are after.
|
269,009 | 269,200 | What is the preferred way to serve web applications written in Lisp? | I've been researching modules for Nginx (my preferred webserver) to serve a Lisp webapp, but I haven't been able to find anything.
Is there modules for Nginx, or is there better ways to serve Lisp webapps? If so, what are they?
| If Nginx support proxying, you could always proxy to a Hunchentoot server running on localhost.
|
275,273 | 275,313 | How do I choose what language to use in DrScheme? | I recently downloaded PLT Scheme and DrScheme. When I open DrScheme, I am told to choose a language. However, I'm not familiar with any of my options, and the help guides don't really break it down to help me easily choose which choice.
So, first - is DrScheme and PLT Scheme really the tools I need to learn Lisp and/or Scheme? If so, what are the different languages and which one(s) should I be using?
| Just go for "Pretty Big". That will be all you need until you know what the rest are for. I find that R5RS is good, but it does lack the extensions that PLT has added to DrScheme.
edit: I just checked and I guess that both "Pretty Big" and "R5RS" are considered "legacy" in DrScheme 4 and the "Module" language is favored instead. Just make sure that all the files you use with the Module language start with
#lang scheme
Module is a way to specify the language used in the source file rather than globally by the DrScheme interpreter. This means that you can use different languages for different parts of your program by breaking it up into files and indicating in each file the language you're using. If you're just starting out, all you need to worry about is just keeping #lang scheme at the top of all the files you use.
A small note - this declaration is not official Scheme, and needs to be removed if you attempt to use the files in another Scheme interpreter.
|
279,696 | 280,299 | Beginner at Common Lisp: Macro Question For Defining Packages on the Fly | Still struggling to understand what best practices are with respect to macros. I'm attempting to write a macro which defines packages on the fly.
(defmacro def-dynamic-package (name)
`(defpackage ,(intern (string-upcase name) "KEYWORD")
(:use :common-lisp)))
This works fine only for expressions such as:
(def-dynamic-package "helloworld")
But fails miserably for something like this:
(defun make-package-from-path (path)
(def-dynamic-package (pathname-name path)))
or
(defun make-package-from-path (path)
(let ((filename (pathname-path)))
(def-dynamic-package filename)))
I understand how most basic macros work but how to implement this one escapes me.
| defpackage is a macro. As such, it's expanded at compile-time, not run-time. What you want is something that is called at run-time in order to make a new package. Therefore, defpackage can't do anything for you.
Fortunately, there's also make-package, which provides defpackage's features as a function. Use it instead of defpackage.
|
282,905 | 629,463 | Are there any good editors for Lisp programming, other than Emacs? | I'm looking for an alternative, since I find emacs difficult to use. I'd rather use an editor that supports all the usual shortcuts I'm used to, such as arrow keys to move the cursor around, CTRL+SHIFT+RightArrow to select the next word, etc.
Basically, I don't want to have to relearn all my familiar shortcuts just so I can use emacs.
Can anyone recommend a suitable editor?
Another thing - Notepad++ supports LISP syntax coloring, but it doesn't have an integrated LISP console like emacs does. Would it be fine to just have a Notepad++ window and a Command Line window open, side-by-side, and use the command-line whenever I want to run my program?
| Try LispIDE. It's kind of rudimentary but may improve things a bit for you.
|
293,040 | 293,118 | Function persistence in Common Lisp | Is there any persistence solution for Common Lisp, such as Elephant, that allows function persistence? Currently my app stores an identifier on the db and later searches in a function table which it is, but this method does not allow dynamically created functions to be stored.
| It's not a database persistence mechanism, but most Common Lisps have a way of writing FASLs for all kinds of objects, including functions. For example:
cl-user(1): (compile (defun hello () (format t "~&Hello~%")))
hello
nil
nil
cl-user(2): (excl:fasl-write (symbol-function 'hello) "/tmp/hello.fasl")
t
cl-user(3): (excl:fasl-read "/tmp/hello.fasl")
(#<Function hello @ #x1000a964d2>)
You can write to a stream (here I used a file for convenience), so you can trivially capture those bytes and stuff them into a database if you wished.
|
293,567 | 293,580 | Side-effects in closures, are they still purely functional? | Being relatively new to functional programming, I expend lots of energy wondering “is this the functional way to do things?” Obviously recursion vs. iteration is pretty straightforward and it’s obvious that recursion is the functional way of doing things. But take closures for instance.
I’ve learned about closures using Lisp and I understand that closures are a combination of a function and an environment (sounds a lot like state and behavior). For instance:
(let ((x 1))
(defun doubleX()
(setf x (* x 2))))
Here we have a function doubleX that has been defined within the environment of the x variable. We could pass this function around to other functions and then invoke it and it will still be able to reference the x variable. The function can continue to refer to that variable, even if it is invoked outside of the environment where the variable has been defined. Many of the examples I’ve seen of closures look like this. Where setf is used to change the value of the lexical variable. This confuses me because:
1.) I thought setf was evil. Mostly because it causes side-effects and apparently they are also evil.
2.) Is this really “functional”? Seems like just a way of keeping global state and I thought functional languages were stateless.
Maybe I just don’t understand closures. Can someone help me out?
| You're right, using closures to manipulate state is not purely functional. Lisp allows you to program in a functional style, but it doesn't force you to. I actually prefer this approach because it allows me to strike a pragmatic balance between purely functional and the convenience of modifying state.
What you might try is to write something that seems functional from the outside but keeps an internal mutable state for efficiency. A great example of this is memoization where you keep a record of all the previous invocations to speed up functions like fibonacci, but since the function always returns the same output for the same input and doesn't modify any external state, it can be considered to be functional from the outside.
|
294,779 | 294,789 | Function names as strings in Lisp? | I have a big list of global variables that each have their own setup function. My goal is to go through this list, call each item's setup function, and generate some stats on the data loaded in the matching variable. However, what I'm trying now isn't working and I need help to make my program call the setup functions.
The global variables and their setup functions are case-sensitive since this came from XML and is necessary for uniqueness.
The data looks something like this:
'(ABCD ABC\d AB\c\d ...)
and the setup functions look like this:
(defun setup_ABCD...
(defun setup_ABC\d...
I've tried concatenating them together and turning the resulting string into a function,
but this interferes with the namespace of the previously loaded setup function. Here's how I tried to implement that:
(make-symbol (concatenate 'string "setup_" (symbol-name(first '(abc\d)))))
But using funcall on this doesn't work. How can I get a callable function from this?
| It's because MAKE-SYMBOL returns an uninterned symbol. You should use INTERN instead.
|
294,852 | 295,510 | References Needed for Implementing an Interpreter in C/C++ | I find myself attached to a project to integerate an interpreter into an existing application. The language to be interpreted is a derivative of Lisp, with application-specific builtins. Individual 'programs' will be run batch-style in the application.
I'm surprised that over the years I've written a couple of compilers, and several data-language translators/parsers, but I've never actually written an interpreter before. The prototype is pretty far along, implemented as a syntax tree walker, in C++. I can probably influence the architecture beyond the prototype, but not the implementation language (C++). So, constraints:
implementation will be in C++
parsing will probably be handled with a yacc/bison grammar (it is now)
suggestions of full VM/Interpreter ecologies like NekoVM and LLVM are probably not practical for this project. Self-contained is better, even if this sounds like NIH.
What I'm really looking for is reading material on the fundamentals of implementing interpreters. I did some browsing of SO, and another site known as Lambda the Ultimate, though they are more oriented toward programming language theory.
Some of the tidbits I've gathered so far:
Lisp in Small Pieces, by Christian Queinnec. The person recommending it said it "goes from the trivial interpreter to more advanced techniques and finishes presenting bytecode and 'Scheme to C' compilers."
NekoVM. As I've mentioned above, I doubt that we'd be allowed to incorporate an entire VM framework to support this project.
Structure and Interpretation of Computer Programs. Originally I suggested that this might be overkill, but having worked through a healthy chunk, I agree with @JBF. Very informative, and mind-expanding.
On Lisp by Paul Graham. I've read this, and while it is an informative introduction to Lisp principles, is not enough to jump-start constructing an interpreter.
Parrot Implementation. This seems like a fun read. Not sure it will provide me with the fundamentals.
Scheme from Scratch. Peter Michaux is attacking various implementations of Scheme, from a quick-and-dirty Scheme interpreter written in C (for use as a bootstrap in later projects) to compiled Scheme code. Very interesting so far.
Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages, recommended in the comment thread for Books On Creating Interpreted Languages. The book contains two chapters devoted to the practice of building interpreters, so I'm adding it to my reading queue.
New (and yet Old, i.e. 1979): Writing Interactive Compilers and Interpreters by P. J. Brown. This is long out of print, but is interesting in providing an outline of the various tasks associated with the implementation of a Basic interpreter. I've seen mixed reviews for this one but as it is cheap (I have it on order used for around $3.50) I'll give it a spin.
So how about it? Is there a good book that takes the neophyte by the hand and shows how to build an interpreter in C/C++ for a Lisp-like language? Do you have a preference for syntax-tree walkers or bytecode interpreters?
To answer @JBF:
the current prototype is an interpreter, and it makes sense to me as we're accepting a path to an arbitrary code file and executing it in our application environment. The builtins are used to affect our in-memory data representation.
it should not be hideously slow. The current tree walker seems acceptable.
The language is based on Lisp, but is not Lisp, so no standards compliance required.
As mentioned above, it's unlikely that we'll be allowed to add a full external VM/interpreter project to solve this problem.
To the other posters, I'll be checking out your citations as well. Thanks, all!
| Short answer:
The fundamental reading list for a lisp interpreter is SICP. I would not at all call it overkill, if you feel you are overqualified for the first parts of the book jump to chapter 4 and start interpreting away (although I feel this would be a loss since chapters 1-3 really are that good!).
Add LISP in Small Pieces (LISP from now on), chapters 1-3. Especially chapter 3 if you need to implement any non-trivial control forms.
See this post by Jens Axel Søgaard on a minimal self-hosting Scheme: http://www.scheme.dk/blog/2006/12/self-evaluating-evaluator.html .
A slightly longer answer:
It is hard to give advice without knowing what you require from your interpreter.
does it really really need to be an interpreter, or do you actually need to be able to execute lisp code?
does it need to be fast?
does it need standards compliance? Common Lisp? R5RS? R6RS? Any SFRIs you need?
If you need anything more fancy than a simple syntax tree walker I would strongly recommend embedding a fast scheme subsystem. Gambit scheme comes to mind: http://dynamo.iro.umontreal.ca/~gambit/wiki/index.php/Main_Page .
If that is not an option chapter 5 in SICP and chapters 5-- in LISP target compilation for faster execution.
For faster interpretation I would take a look at the most recent JavaScript interpreters/compilers. There seem to be a lot of thought going into fast JavaScript execution, and you can probably learn from them. V8 cites two important papers: http://code.google.com/apis/v8/design.html and squirrelfish cites a couple: http://webkit.org/blog/189/announcing-squirrelfish/ .
There is also the canonical scheme papers: http://library.readscheme.org/page1.html for the RABBIT compiler.
If I engage in a bit of premature speculation, memory management might be the tough nut to crack. Nils M Holm has published a book "Scheme 9 from empty space" http://www.t3x.org/s9fes/ which includes a simple stop-the-world mark and sweep garbage collector. Source included.
John Rose (of newer JVM fame) has written a paper on integrating Scheme to C: http://library.readscheme.org/servlets/cite.ss?pattern=AcmDL-Ros-92 .
|
309,440 | 310,182 | Lisp In A Box - Why is it starting a server? | I've decided to get back into LISP (haven't used it since my AI classes) to get more comfortable with functional programming in general, so I downloaded Lisp In A Box (which we actually used in a previous class) which comes with CLISP and Emacs.
When I run it, it says:
Connected on port 1617. Take this REPL, brother, and may it serve you well.
What the? So I looked on the Lisp In A Box webpage more closely and found this:
SLIME is an integrated development environment for Emacs which interfaces with a Common Lisp implementation over a network socket. Lots of information about SLIME can be found at the SLIME node on CLiki. The manual for SLIME is available in PDF format online.
I somewhat understand what SLIME is (some sort of extension to emacs, right?) But why in the world is a text editor starting its own server and connecting to it?
| Sockets are more flexible than pipes. For one, SLIME lets you connect to Swank servers on the network, which is very useful for doing live fixes on remote machines with long-running processes (such as web servers). Given this, why would you add another layer of complexity by abstracting communication in such a way as to support both pipes and sockets? It's not like pipes are any simpler to program than sockets, anyway.
|
318,785 | 318,913 | Emacs mode that highlight Lisp forms | What is the Emacs mode or package that highlights Lisp forms changing the color of the backgrounds so that the form you are in has one color, the outer form another, the outer outer form another and so on?
| You may want to try mwe-color-box (screenshot below) or read Five approaches to s-expression highlighting by Lemondor.
(source: foldr.org)
|
318,952 | 319,029 | Convert string to code in Scheme | How do I convert a string into the corresponding code in PLT Scheme (which does not contain the string->input-port method)? For example, I want to convert this string:
"(1 (0) 1 (0) 0)"
into this list:
'(1 (0) 1 (0) 0)
Is it possible to do this without opening a file?
| Scheme has procedure read for reading s-expressions from input port and you can convert a string to input stream with string->input-port. So, you can read a Scheme object from a string with
(read (string->input-port "(1 (0) 1 (0) 0)"))
I don't have Scheme installed, so I only read it from reference and didn't actually test it.
|
330,371 | 330,582 | Are Databases and Functional Programming at odds? | I've been a web developer for some time now, and have recently started learning some functional programming. Like others, I've had some significant trouble apply many of these concepts to my professional work. For me, the primary reason for this is I see a conflict between between FP's goal of remaining stateless seems quite at odds with that fact that most web development work I've done has been heavily tied to databases, which are very data-centric.
One thing that made me a much more productive developer on the OOP side of things was the discovery of object-relational mappers like MyGeneration d00dads for .Net, Class::DBI for perl, ActiveRecord for ruby, etc. This allowed me to stay away from writing insert and select statements all day, and to focus on working with the data easily as objects. Of course, I could still write SQL queries when their power was needed, but otherwise it was abstracted nicely behind the scenes.
Now, turning to functional-programming, it seems like with many of the FP web frameworks like Links require writing a lot of boilerplate sql code, as in this example. Weblocks seems a little better, but it seems to use kind of an OOP model for working with data, and still requires code to be manually written for each table in your database as in this example. I suppose you use some code generation to write these mapping functions, but that seems decidedly un-lisp-like.
(Note I have not looked at Weblocks or Links extremely closely, I may just be misunderstanding how they are used).
So the question is, for the database access portions (which I believe are pretty large) of web application, or other development requiring interface with a sql database we seem to be forced down one of the following paths:
Don't Use Functional Programming
Access Data in an annoying, un-abstracted way that involves manually writing a lot of SQL or SQL-like code ala Links
Force our functional Language into a pseudo-OOP paradigm, thus removing some of the elegance and stability of true functional programming.
Clearly, none of these options seem ideal. Has found a way circumvent these issues? Is there really an even an issue here?
Note: I personally am most familiar with LISP on the FP front, so if you want to give any examples and know multiple FP languages, lisp would probably be the preferred language of choice
PS: For Issues specific to other aspects of web development see this question.
| First of all, I would not say that CLOS (Common Lisp Object System) is "pseudo-OO". It is first class OO.
Second, I believe that you should use the paradigm that fits your needs.
You cannot statelessly store data, while a function is flow of data and does not really need state.
If you have several needs intermixed, mix your paradigms. Do not restrict yourself to only using the lower right corner of your toolbox.
|
334,691 | 340,089 | The tool for visual programming | I need the tool for graphical representing of work flow in a program (like electronic circuits are described with graphical representation). The representation has to be like the following: functions are boxes and arrows between boxes are "messages". Like this:
alt text http://img372.imageshack.us/img372/8471/functionsqv0.png
This picture shows the following: (c (a) (b))
Where parameters of c() are named as d and e. On C it would be
void c( someType1 d, someType2 e );
someType1 a( void );
someType2 b( void );
....
c( a(), b() );
So I think that I need the tool for manipulation and visual representation of s-expressions like these:
(a (b c d) e)
or
f(g(z(x,y))+5)
It is not about linked lists, it is about logical connections between functions.
The tool has only to generate the textual representation from graphical one.
Well, I've found a lot of stuff on the Wiki page about the "Visual programming" and "Graphical programming" and so on. Mostly all described tools are cool, but somewhat complicated. And the list is pretty long, so it would take a lot of time to test all of them. So I need an opinion of real, alive people.
Requirements are:
Free
Simple
Can export to at least one real
language like XML or C++ or LISP or any
other.
And it would be really good if this tool were configurable.
I like the FlowDesigner tool: it seems to be almost the thing I need, but it cannot export to any language... Alas.
UPD: The wiki page I mentioned: Graphical Programming
UPD2: well, I decided to write my own tool...
| What about using something like Graphviz?
|
340,989 | 341,002 | Elisp performance on Windows and Linux | I have the following dead simple elisp functions; the first removes the fill breaks from the current paragraph, and the second loops through the current document applying the first to each paragraph in turn, in effect removing all single line-breaks from the document. It runs fast on my low-spec Puppy Linux box using emacs 22.3 (10 seconds for 600 pages of Thomas Aquinas), but when I go to a powerful Windows XP machine with emacs 21.3, it takes almost an hour to do the same document. What can I do to make it run as well on the Windows machine with emacs 21.3?
(defun remove-line-breaks ()
"Remove line endings in a paragraph."
(interactive)
(let ((fill-column 90002000))
(fill-paragraph nil)))
:
(defun remove-all-line-breaks ()
"Remove all single line-breaks in a document"
(interactive)
(while (not (= (point) (buffer-end 1)))
(remove-line-breaks)
(next-line 1)))
Forgive my poor elisp; I'm having great fun learning Lisp and starting to use the power of emacs, but I'm new to it yet.
| As the first try, you should download and install Emacs 22.3 for your Windows box and then compare the speed.
Speed difference shouldn't be that big after upgrade.
|
369,122 | 369,332 | "Don't know how to create ISeq from: Symbol" error in Clojure | I have the following Clojure code and I'm not sure why it's not working:
(defn match (x y &optional binds)
(cond
((eql x y) (values binds t))
((assoc x binds) (match (binding x binds) y binds))
((assoc y binds) (match x (binding y binds) binds))
((var? x) (values (cons (cons x y) binds) t))
((var? y) (values (cons (cons y x) binds) t))
(t
(when (and (consp x) (consp y))
(multiple-value-bind (b2 yes)
(match (car x) (car y) binds)
(and yes (match (cdr x) (cdr y) b2)))))))
(The code is translated from Paul Graham's ANSI Common Lisp book.)
When I run it, I get the following error:
java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
clojure.lang.Compiler$CompilerException: NO_SOURCE_FILE:2: java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.Compiler.analyze(Compiler.java:3713)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:3848)
at clojure.lang.Compiler.analyze(Compiler.java:3698)
at clojure.lang.Compiler.access$200(Compiler.java:37)
at clojure.lang.Compiler$DefExpr$Parser.parse(Compiler.java:343)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:3858)
at clojure.lang.Compiler.analyze(Compiler.java:3698)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:3848)
at clojure.lang.Compiler.analyze(Compiler.java:3698)
at clojure.lang.Compiler.analyze(Compiler.java:3671)
at clojure.lang.Compiler.eval(Compiler.java:3895)
at clojure.lang.Repl.main(Repl.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at jline.ConsoleRunner.main(ConsoleRunner.java:69)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.LazyCons.rest(LazyCons.java:64)
at clojure.lang.ASeq.count(ASeq.java:85)
at clojure.lang.RT.count(RT.java:486)
at clojure.lang.Cons.count(Cons.java:41)
at clojure.lang.Compiler.analyze(Compiler.java:3695)
... 16 more
Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.LazyCons.first(LazyCons.java:44)
at clojure.lang.LazyCons.rest(LazyCons.java:59)
... 20 more
Caused by: java.lang.IllegalArgumentException: Don't know how to create ISeq from: Symbol
at clojure.lang.RT.seqFrom(RT.java:465)
at clojure.lang.RT.seq(RT.java:448)
at clojure.seq__28.invoke(boot.clj:92)
at clojure.every_QMARK___596.invoke(boot.clj:1180)
at clojure.fn__1147$psig__1149.invoke(boot.clj:2155)
at clojure.map__602$fn__605.invoke(boot.clj:1214)
at clojure.lang.LazyCons.first(LazyCons.java:40)
... 21 more
What am I doing wrong here?
| The problem is that I'm using parentheses ('(' and ')'), rather than square brackets ('[' and ']'), for the arguments list.
It should start out like this:
(defn match [x y &optional binds]
(I found the answer in Programming Clojure by Stuart Halloway.)
|
378,972 | 379,071 | How do I make an Emacs keybinding to set a variable? | I've got a variable in Emacs called my-var that I'd like to set whenever I press C-v. How do I do that? I tried this:
(defun set-my-var (value)
"set my var"
(interactive)
(defvar my-var value
"a variable of mine")
)
(global-set-key "\C-v" 'set-my-var)
But that fails:
call-interactively: Wrong number of arguments: (lambda (value) "set my var"
(interactive) (defvar my-var value "a variable of mine")), 0
| Actually, defvar doesn't do what you think it does either: it only changes the value IF there was no value before. Here's a chunk that does what you're looking for, using the CTRL-u argument:
(defun set-my-var (value)
"Revised version by Charlie Martin"
(interactive "p")
(setq my-var value))
and here's an example, code from the *scratch* buffer
(defun set-my-var (value)
"Revised version by Charlie Martin"
(interactive "p")
(setq my-var value)) ; do ^J to evaluate the defun form, showing return in the buffer.
set-my-var
(global-set-key "\C-v" 'set-my-var)
set-my-var
;Another ^J
;;; Now, what's the value after ^U^V?
my-var
4
;;; Now ^U 8 ^V
my-var
8
;;; now ^U^U^V
my-var
16
|
379,136 | 379,970 | Can I extend lisp with c++? | Can I call a function from lisp from a library written in c or c++? How can I extend lisp?
This is useful when you want to do some system calls or stuff like that.
| It is unusual to call non-lisp code from lisp, and rarely necessary. CLX (the X11 client implementation for CL) doesn't link to the Xlib implementation but "speaks" X11 directly. On any system, your CL implementation is likely to already have excellent operating system hooks rendering this unnecessary.
That said, the answer depends on the lisp implementation:
In ECL you can actually host a CL environment under C and simply call cl_eval() with the code to execute. This can let you write your application (or application host) in C (or C++) and "call to" lisp code.
In CCL, there is a C-compatible calling interface which lets you do something like this:
(with-cstrs ((x "Hello World"))
(#_puts x))
In most other CL implementations (like SBCL; and yes this works in ECL and CCL as well) you can use UFFI (or CFFI) which simply lets you call C functions, which is what other people are talking about. If this is all you want to do, then CFFI is a good, safe place to start.
|
384,419 | 384,716 | LISP Displaying binary tree level by level | I have a list that looks like (A (B (C D)) (E (F))) which represents this tree:
A
/ \
B E
/ \ /
C D F
How do I print it as (A B E C D F) ?
This is as far as I managed:
((lambda(tree) (loop for ele in tree do (print ele))) my-list)
But it prints:
A
(B (C D))
(E (F))
NIL
I'm pretty new to Common LISP so there may be functions that I should've used. If that's the case then enlight me.
Thanks.
| Taking your question at face value, you want to print out the nodes in 'breadth-first' order, rather than using one of the standard, depth-first orderings: 'in-order' or 'pre-order' or 'post-order'.
in-order: C B D A E F
pre-order: A B C D E F
post-order: C D B F E A
requested order: A B E C D F
In your tree structure, each element can be either an atom, or a list with one element, or a list with two elements. The first element of a list is always an atom.
What I think the pseudo-code needs to look like is approximately:
Given a list 'remains-of-tree':
Create empty 'next-level' list
Foreach item in `remains-of-tree`
Print the CAR of `remains-of-tree`
If the CDR of `remains-of-tree` is not empty
CONS the first item onto 'next-level'
If there is a second item, CONS that onto `next-level`
Recurse, passing `next-level` as argument.
I'm 100% sure that can be cleaned up (that looks like trivial tail recursion, all else apart). However, I think it works.
Start: (A (B (C D)) (E (F)))
Level 1:
Print CAR: A
Add (B (C D)) to next-level: ((B (C D)))
Add (E (F)) to next-level: ((B (C D)) (E (F)))
Pass ((B (C D) (E (F))) to level 2:
Level 2:
Item 1 is (B (C D))
Print CAR: B
Push C to next-level: (C)
Push D to next-level: (C D)
Item 2 is (E (F))
Print CAR: E
Push F to next-level: (C D F)
Pass (C D F) to level 3:
Level 3:
Item 1 is C
Print CAR: C
Item 2 is D
Print CAR: D
Item 3 is F
Print CAR: F
|
386,854 | 464,210 | How do you type lisp efficiently, with so many parentheses? | I try to keep my fingers on home row as much as possible.
Typing all the parentheses makes me move away from there a fair bit.
I use Emacs; the parentheses themselves are no issue, I'm comfortable with them. And I don't like modes that type them for me automatically.
I've thought about remapping the square brackets to parentheses and vice versa. Is this a good idea? What does everyone else do?
| I would personally recommend the lethal combo of Emacs, SLIME & paredit.el
Paredit allows you to pseudo-semantically edit the LISP code at sexp level, and that makes the parentheses disappear almost completely. You can move around sexps as if they are simple words and even mutate them with just a couple of key-strokes. There is also a minor mode called Redshank which works in conjunction with Paredit and that provides more power.
Consider simple these examples (| is the position of the cursor):
(foo bar (baz| quux) zot) + C-( => (foo (bar baz| quux) zot)
(foo (bar |baz) quux zot) + C-) => (foo (bar |baz quux) zot)
(foo (bar baz |quux) zot) + C-{ => (foo bar (baz |quux) zot)
(foo (bar |baz quux) zot) + C-} => (foo (bar |baz) quux zot)
I have done some serious Common Lisp programming in my time, and paredit has proved to be invaluable to me. I can't even think of writing non-trivial LISP code without my toolbox. And after all that's the way it should be; you should never have to count or match your parentheses... once you master Paredit, the parentheses will just disappear from in front of your eyes.
Remapping the [] to () will help, but you will stop caring much after you start using Paredit.
Feel free to use the LISP specific portions from my dot-emacs.
|
398,579 | 398,585 | What's the best way to learn LISP? | I have been programming in Python, PHP, Java and C for a couple or years now, and I just finished reading Hackers and Painters, so I would love to give LISP a try!
I understand its totally diferent from what i know and that it won't be easy. Also I think (please correct me if I'm wrong) there's way less community and development around LISP. So my question is: what's the best way to learn LISP?
I wouldn't mind buying books or investing some time. I just don't want it to be wasted.
The "final" idea would be to use LISP for web development, and I know that's not so common so... I know it's good to plan my learning before picking the first book or tutorial and spending lots of time on something that may not be the best way!
Thank you all for your answers!
edit: I read Practical Common Lisp and was: ... long, hard, interesting and definitely got me rolling in Lisp, after that i read the little schemer, and it was short, fun and very very good for my overall programming. So my recommendation would be to read first the little schemer, then (its a couple of hours and its worth it) if you decide lisp(or scheme or whatever dialect) is not what you where looking for, you will still have a very fun new way of thinking about recursion!
| Try reading Practical Common Lisp, by Peter Seibel.
|
405,165 | 405,188 | Please advise on Ruby vs Python, for someone who likes LISP a lot | I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.
Which one is closer to LISP: Python or Ruby?
I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?
PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.
| I'd go with Ruby. It's got all kinds of metaprogramming and duck punching hacks that make it really easy to extend. Features like blocks may not seem like much at first, but they make for some really clean syntax if you use them right. Open classes can be debugging hell if you screw them up, but if you're a responsible programmer, you can do things like 2.days.from_now (example from Rails) really easily (Python can do this too, I think, but with a bit more pain)
PS: Check out "Why Ruby is an acceptable LISP".
|
406,426 | 406,455 | Logical Languages - Prolog or Lisp/Smalltalk or something else? | So, I am writing some sort of a statistics program (actually I am redesigning it to something more elegant) and I thought I should use a language that was created for that kind of stuff (dealing with huge data of stats, connections between them and some sort of genetic/neural programming).
To tell you the truth, I just want an excuse to dive into lisp/smalltalk (aren't smalltalk/lisp/clojure the same? - like python and ruby? -semantics-wise) but I also want a language to be easily understood by other people that are fond of the BASIC language (that's why I didn't choose LISP - yet :D).
I also checked Prolog and it seems a pretty cool language (easy to do relations between data and easier than Lisp) but I'd like to hear what you think.
Thx
Edit:
I always confuse common lisp with Smalltalk. Sorry for putting these two langs together. Also what I meant by "other people that are fond of the BASIC language" is that I don't prefer a language with semantics like lisp (for people with no CS background) and I find Prolog a little bit more intuitive (but that's my opinion after I just messed a little bit with both of them).
| Is there any particular reason not to use R? It's sort of a build vs. buy (or in this case download) decision. If you're doing a statistical computation, R has many packages off the shelf. These include many libraries and interfaces for various types of data sources. There are also interface libraries for embedding R in other languages such as Python, so you can build a hybrid application with a GUI in Python (for example) and a core computation engine using R.
In this case, you could possibly reduce the effort needed for implementation and wind up with a more flexible application.
If you've got your heart set on learning another language, by all means, do it. There are several good free (some as in speech, some as in beer) implementations of Smalltalk, Prolog and LISP.
If you're putting a user interface on the system, Smalltalk might be the better option. If you want to create large rule sets as a part of your application, Prolog is designed for this sort of thing. Various people have written about the LISP ephiphany that influences the way you think about programming but I can't really vouch for this from experience - I've only really used AutoLISP for writing automation scripts on AutoCAD.
|
407,658 | 409,281 | How to save all functions I entered in LispBox/Slime? | Situation: I entered several functions while working with REPL in Emacs.
Problem: There is junk like "; Evaluation aborted" when I'm simply saving buffer.
What I want: clear descriptions of all the functions I entered in their latest revision.
Can I do that? Thanks.
| I agree that the best work flow method is to write your code in a separate buffer and evaluate in that, rather than enter the functions in the repl.
Assuming you have gone the repl way, I guess, C. Martin's solution to save the repl log and manually go through it are your only options.
If you entered the functions and vars into a separate package, you could go through the symbols in the package to help you decide what you want to keep.
E.g. to see all symbols created in the cl-user package:
(let ((p (find-package :cl-user)))
(loop
for s being the symbols in p
when (eq p (symbol-package s))
do (format t "~a~%" s)))
|
420,300 | 425,000 | Lisp: Need help getting correct behaviour from SBCL when converting octet stream to EUC-JP with malformed bytes | The following does not work in this particular case, complaining that whatever you give it is not a character.
(handler-bind ((sb-int:character-coding-error
#'(lambda (c)
(invoke-restart 'use-value #\?))))
(sb-ext:octets-to-string *euc-jp* :external-format :euc-jp))
Where *euc-jp* is a variable containing binary of EUC-JP encoded text.
I have tried #\KATAKANA_LETTER_NI as well, instead of #\? and also just "". Nothing has worked so far.
Any help would be greatly appreciated!
EDIT: To reproduce *EUC-JP*, fetch http://blogs.yahoo.co.jp/akira_w0325/27287392.html using drakma.
| There's an expression in SBCL 1.0.18's mb-util.lisp that looks like this:
(if code
(code-char code)
(decoding-error array pos (+ pos bytes) ,format
',malformed pos))
I'm not very familiar with SBCL's internals, but this looks like a bug. The consequent returns a character, while the alternative returns a string (no matter what you give to it via USE-VALUE, it's always converted into a string by way of the STRING function; see the definition of DECODING-ERROR in octets.lisp).
|
426,991 | 427,020 | LISP very simple list question | Im learning lisp and im pretty new at this so i was wondering...
if i do this:
(defparameter *list-1* (list 1 2))
(defparameter *list-2* (list 2 3))
(defparameter *list-3* (append *list-1* *list-2*))
And then
(setf (first *list-2*) 1)
*list-3*
I will get (1 2 1 4)
I know this is because the append is going to "save resources" and create a new list for the first chunk, but will actually just point to the second chunk, coz if i do:
(setf (first *list-1*) 0)
*list-3*
I will get (1 2 1 4) instade of the more logical (0 2 1 4)
So my question is, what other cases are like this in lisp, how do you black belt lispers know how to deal with this stuff that is not intuitive or consistent?
| One defensive tactic is to avoid sharing structure.
(defparameter *list-3* (append *list-1* *list-2* '()))
or
(defparameter *list-3* (append *list-1* (copy-list *list-2*)))
Now the structure of the new *list-3* is all new, and modifications to *list-3* won't affect *list-2* and vice versa.
|
427,332 | 427,333 | asdf-installing libraries from the command-line | Coming from a Perl background, I have to say I prefer cpan Foo::Bar to the having to start sbcl, (require :asdf-install) and finally (asdf-install:install :foo-bar). Is there anything more convenient than this around?
| There is clbuild:
http://common-lisp.net/project/clbuild/
But I add this to my .bashrc:
function asdf_install {
sbcl --eval "(asdf:operate 'asdf:load-op :asdf-install)" --eval "(asdf-install:install :$1)" --eval "(quit)"
}
function asdf_oos {
rlwrap sbcl --eval "(asdf:operate 'asdf:$2 :$1)"
}
|
437,312 | 437,584 | Trying to learn: Object Reorientation, and generic functions in LISP! | im reading Practical common Lisp as a result of another question.
I just read chapter 16 and 17 where you can find how LISP manages objects. But after a couple of years of thinking how Java manages objects, i cant really seem to understand how you would implement bigger architectures in LISP using the CLOS.
So i ask you guys for some 20-50 pages reading about CLOS applied to bigger architectures than simple examples. Maybe a couple of blogpost or even experiences!
TY
| Perhaps take a look at the example applications that are walked through in the later chapters. You will see that classes and objects are just another tool in your box. Resist the urge to program Java with Lisp syntax.
Another place to look at is Successful Lisp, chapters 7 and 14 for the basics, and chapters 31 and a part of 3.10 are about packages and handling large projects.
Some Lisp guru (it might have been Paul Graham, but I am not sure) once said that he has not needed CLOS at all yet.
edit: I think that your confusion may come from the fact that in Lisp, you do not use the class system for organizing namespaces. This is done separately; the two do not really have anything to do with each other.
|
445,594 | 445,807 | Weird HTTP problem/mistake with Lisp | I'm attempting to learn a little more about handling sockets and network connections in SBCL; so I wrote a simple wrapper for HTTP. Thus far, it merely makes a stream and performs a request to ultimately get the header data and page content of a website.
Until now, it has worked at somewhat decently. Nothing to brag home about, but it at least worked.
I have come across a strange problem, however; I keep getting "400 Bad Request" errors.
At first, I was somewhat leery about how I was processing the HTTP requests (more or less passing a request string as a function argument), then I made a function that formats a query string with all the parts I need and returns it for use later... but I still get errors.
What's even more odd is that the errors don't happen every time. If I try the script on a page like Google, I get a "200 Ok" return value... but at other times on other sites, I'll get "400 Bad Request".
I'm certain its a problem with my code, but I'll be damned if I know exactly what is causing it.
Here is the code that I am working with:
(use-package :sb-bsd-sockets)
(defun read-buf-nonblock (buffer stream)
(let ((eof (gensym)))
(do ((i 0 (1+ i))
(c (read-char stream nil eof)
(read-char-no-hang stream nil eof)))
((or (>= i (length buffer)) (not c) (eq c eof)) i)
(setf (elt buffer i) c))))
(defun http-connect (host &optional (port 80))
"Create I/O stream to given host on a specified port"
(let ((socket (make-instance 'inet-socket
:type :stream
:protocol :tcp)))
(socket-connect
socket (car (host-ent-addresses (get-host-by-name host))) port)
(let ((stream (socket-make-stream socket
:input t
:output t
:buffering :none)))
stream)))
(defun http-request (stream request &optional (buffer 1024))
"Perform HTTP request on a specified stream"
(format stream "~a~%~%" request )
(let ((data (make-string buffer)))
(setf data (subseq data 0
(read-buf-nonblock data
stream)))
(princ data)
(> (length data) 0)))
(defun request (host request)
"formated HTTP request"
(format nil "~a HTTP/1.0 Host: ~a" request host))
(defun get-page (host &optional (request "GET /"))
"simple demo to get content of a page"
(let ((stream (http-connect host)))
(http-request stream (request host request)))
| A few things. First, to your concern about the 400 errors you are getting back, a few possibilities come to mind:
"Host:" isn't actually a valid header field in HTTP/1.0, and depending on how fascist the web server you are contacting is about standards, it would reject this as a bad request based on the protocol you claim to be speaking.
You need a CRLF between your Request-line and each of the header lines.
It is possible that your (request) function is returning something for the Request-URI field -- you substitute in the value of request as the contents of this part of the Request-line -- that is bogus in one way or another (badly escaped characters, etc.). Seeing what it is outputting might help out some.
Some other more general pointer to help you along your way:
(read-buf-nonblock) is very confusing. Where is the symbol 'c' defined? Why is 'eof' (gensym)ed and then not assigned any value? It looks very much like a byte-by-byte copy taken straight out of an imperative program, and plopped into Lisp. It looks like what you have reimplemented here is (read-sequence). Go look here in the Common Lisp Hyperspec, and see if this is what you need. The other half of this is to set your socket you created to be non-blocking. This is pretty easy, even though the SBCL documentation is almost silent on the topic. Use this:
(socket-make-stream socket
:input t
:output t
:buffering :none
:timeout 0)
The last (let) form of (http-connect) isn't necessary. Just evaluate
(socket-make-stream socket
:input t
:output t
:buffering :none)
without the let, and http-connect should still return the right value.
In (http-request)...
Replace:
(format stream "~a~%~%" request )
(let ((data (make-string buffer)))
(setf data (subseq data 0
(read-buf-nonblock data
stream)))
(princ data)
(> (length data) 0)))
with
(format stream "~a~%~%" request )
(let ((data (read-buf-nonblock stream)))
(princ data)
(> (length data) 0)))
and make (read-buf-nonblock) return the string of data, rather that having it assign within the function. So where you have buffer being assigned, create a variable buffer within and then return it. What you are doing is called relying on "side-effects," and tends to produce more errors and harder to find errors. Use it only when you have to, especially in a language that makes it easy not to depend on them.
I mostly like the the way get-page is defined. It feels very much in the functional programming paradigm. However, you should either change the name of the (request) function, or the variable request. Having both in there is confusing.
Yikes, hands hurt. But hopefully this helps. Done typing. :-)
|
459,323 | 459,381 | What is the best Scheme or LISP implementation for OS X? | I am looking for a version of Scheme or even LISP that I can use to recover some lost Lisp development skills. Some web capabilities would be nice but not essential.
I've looked at Plt and MIT scheme and, while both look pretty good, the Plt seems to be more feature rich. I've also looked at Lisp implementations but all of the seem quite expensive.
I favor free/inexpensive implementations as this is truly likely to just be occasional hobby programming. What recommendations would you have?
| I'd go with Racket. It may not be as fast as SBCL, but it does have excellent libraries and documentation, as well as an integrated environment that's designed to get you developing and running Scheme programs right out of the gate. What I really like about Racket's IDE, DrRacket, is what you don't have to do—you don't have to learn Emacs, you don't have to learn SLIME, you don't have to worry about hunting down third-party libraries, as virtually all libraries meant for Racket can be found in packages. All in all, it really cuts down on the learning curve and allows you to focus on the actual task at hand: writing great code.
Also, it comes with a web server if you want to make Racket-powered websites (which I'm currently looking into).
|
463,463 | 463,837 | Dynamic and Lexical variables in Common Lisp | I am reading the book 'Practical Common Lisp' by Peter Seibel.
In Chapter 6, "Variables" sections
"Lexical Variables and Closures" and "Dynamic, a.k.a. Special, Variables".
http://www.gigamonkeys.com/book/variables.html
My problem is that the examples in both sections show how (let ...) can shadow global variables and doesn't really tell the difference between the Dynamic and Lexical vars.
I understand how closures work but I don't really get whats so special about let in this example:
(defvar *x* 10)
(defun foo ()
(format t "Before assignment~18tX: ~d~%" *x*)
(setf *x* (+ 1 *x*))
(format t "After assignment~18tX: ~d~%" *x*))
(defun bar ()
(foo)
(let ((*x* 20)) (foo))
(foo))
CL-USER> (foo)
Before assignment X: 10
After assignment X: 11
NIL
CL-USER> (bar)
Before assignment X: 11
After assignment X: 12
Before assignment X: 20
After assignment X: 21
Before assignment X: 12
After assignment X: 13
NIL
I feel like there is nothing special is going on here. The outer foo in bar increments the global x, and foo surrounded by let in bar increments the shadowed x. What's the big deal? I don't see how is this supposed to explain the difference between lexical and dynamic variables. Yet the book continues like this:
So how does this work? How does LET
know that when it binds x it's
supposed to create a dynamic binding
rather than a normal lexical binding?
It knows because the name has been
declared special.12 The name of every
variable defined with DEFVAR and
DEFPARAMETER is automatically declared
globally special.
What would happen if let would bind x using "normal lexical binding"? All in all, what are the differences between dynamic and lexical binding and how is this example special regarding dynamic binding?
| When a variable is lexically scoped, the system looks to where the function is defined to find the value for a free variable. When a variable is dynamically scoped, the system looks to where the function is called to find the value for the free variable. Variables in Common Lisp are all lexical by default; however, dynamically scoped variables can be defined at the top level using defvar or defparameter.
A simpler example
lexical scoping (with setq):
(setq x 3)
(defun foo () x)
(let ((x 4)) (foo)) ; returns 3
dynamic scoping (with defvar):
(defvar x 3)
(defun foo () x)
(let ((x 4)) (foo)) ; returns 4
How does the let know if a variable is lexical or dynamic? It doesn't. On the other hand, when foo goes to find the value of X, it will initially find the lexical value defined at the top level. It then checks to see if the variable is supposed to be dynamic. If it is, then foo looks to the calling environment, which, in this case, uses let to overshadow the value of X to be 4.
(note: this is an oversimplification, but it will help to visualize the difference between the different scoping rules)
|
473,967 | 474,031 | What is the best approach for a tail-optimized function for calculating the length of a list? | Here is an example that a forum poster gave, I can't tell if this tail optimized. Also, could someone give a laymans description of how a tail optimized version would trump the normal version.
(defun mylength (s)
(labels ((mylength-inner (s x)
(if (car s) (mylength-inner (cdr s) (+ x 1)) x)))
(mylength-inner s 0)))
A non tail optimized version?
(defun l (s) (if (car s) (+ 1 (l (rest s))) 0))
| A function can be tail-call optimized if it returns a straight call to itself or no call to itself. The function mylength-inner will return either x or (mylength-inner (cdr s) (+ x 1)), and so it can be tail-optimized.
This means the compiler can turn it into a loop instead of calling the function recursively. Either return x, or assign (cdr s) to s, increment x, and start again at the top. (The Scheme standard requires that implementations be able to do this optimization, while the Common Lisp standard leaves it up to the implementation. Of course, this optimization is a very useful thing, so most implementations will do it.)
In the non-optimized version, l doesn't just return a call to l, but rather the result of a call to l with one added. This means it can't be directly turned into a loop, so all the function calls will have to be made.
Suppose the compiler wanted to turn l into a loop. There's no problem with the assignment of (rest s) to s, but where does it put the (1 + ...)?
|
480,083 | 585,784 | What is a Lisp image? | Essentially, I would like to know what a Lisp image is? Is it a slice of memory containing the Lisp interpreter and one or more programs or what?
| The Lisp image as dumped memory
The image is usually a file. It is a dump of the memory of a Lisp system. It contains all functions (often compiled to machine code), variable values, symbols, etc. of the Lisp system. It is a snapshot of a running Lisp.
To create an image, one starts the Lisp, uses it for a while and then one dumps an image (the name of the function to do that depends on the implementation).
Using a Lisp image
Next time one restarts Lisp, one can use the dumped image and gets a state back roughly where one was before. When dumping an image one can also tell the Lisp what it should do when the dumped image is started. That way one can reconnect to servers, open files again, etc.
To start such a Lisp system, one needs a kernel and an image. Sometimes the Lisp can put both into a single file, so that an executable file contains both the kernel (with some runtime functionality) and the image data.
On a Lisp Machine (a computer, running a Lisp operating system) a kind of boot loader (the FEP, Front End Processor) may load the image (called 'world') into memory and then start this image. In this case there is no kernel and all that is running on the computer is this Lisp image, which contains all functionality (interpreter, compiler, memory management, GC, network stack, drivers, ...). Basically it is an OS in a single file.
Some Lisp systems will optimize the memory before dumping an image. They may do a garbage collection, order the objects in memory, etc.
Why use images?
Why would one use images? It saves time to load things and one can give preconfigured Lisp systems with application code and data to users. Starting a Common Lisp implementation with a saved image is usually fast - a few milliseconds on a current computer.
Since the Lisp image may contain a lot of functionality (a compiler, even a development environment, lots of debugging information, ...) it is typically several megabytes in size.
Using images in Lisp is very similar to what Smalltalk systems do. Squeak for example also uses an image of Smalltalk code and data and a runtime executable. There is a practical difference: most current Lisp systems use compiled machine code. Thus the image is not portable between different processor architectures (x86, x86-64, SPARC, POWER, ARM, ...) or even operating systems.
History
Such Lisp images have been in use since a long time. For example the function SYSOUT in BBN Lisp from 1967 created such an image. SYSIN would read such an image at start.
Examples for functions saving images
For an example see the function save-image of LispWorks or read the SBCL manual on saving core images.
|
481,803 | 481,858 | Converting some LISP to C# | I'm reading Paul Graham's A Plan for Spam and want to understand it better but my LISP is really rusty. He has a snippet of code that calculates probability as such:
(let ((g (* 2 (or (gethash word good) 0)))
(b (or (gethash word bad) 0)))
(unless (< (+ g b) 5)
(max .01
(min .99 (float (/ (min 1 (/ b nbad))
(+ (min 1 (/ g ngood))
(min 1 (/ b nbad)))))))))
My question is twofold: (1) is there a web resource that will convert LISP to a different language? (my preference would be a C based language) or failing that (2) can someone rewrite that code snippet in C# for me?
| I think it's something like this (warning, possible errors ahead. This snippet is intended as a guide, not a solution):
var g = 2 * (gethash(word, good) | 0);
var b = gethash(word, bad) | 0;
if( (g + b) >= 5)
{
return Math.Max(
0.01,
Math.Min(0.99,
Math.Min(1, b / nbad) /
(Math.Min(1, g / ngood) + Math.Min(1, b / nbad))));
}
|
486,360 | 486,523 | Uses for both static strong typed languages like Haskell and dynamic (strong) languages like Common LIsp | I was working with a Lisp dialect but also learning some Haskell as well. They share some similarities but the main difference in Common Lisp seems to be that you don't have to define a type for each function, argument, etc. whereas in Haskell you do. Also, Haskell is mostly a compiled language. Run the compiler to generate the executable.
My question is this, are there different applications or uses where a language like Haskell may make more sense than a more dynamic language like Common Lisp. For example, it seems that Lisp could be used for more bottom programming, like in building websites or GUIs, where Haskell could be used where compile time checks are more needed like in building TCP/IP servers or code parsers.
Popular Lisp applications:
Emacs
Popular Haskell applications:
PUGS
Darcs
Do you agree, and are there any studies on this?
| Programming languages are tools for thinking with. You can express any program in any language, if you're willing to work hard enough. The chief value provided by one programming language over another is how much support it gives you for thinking about problems in different ways.
For example, Haskell is a language that emphasizes thinking about your problem in terms of types. If there's a convenient way to express your problem in terms of Haskell's data types, you'll probably find that it's a convenient language to write your program in.
Common Lisp's strengths (which are numerous) lie in its dynamic nature and its homoiconicity (that is, Lisp programs are very easy to represent and manipulate as Lisp data) -- Lisp is a "programmable programming language". If your program is most easily expressed in a new domain-specific language, for example, Lisp makes it very easy to do that. Lisp (and other dynamic languages) are a good fit if your problem description deals with data whose type is poorly specified or might change as development progresses.
Language choice is often as much an aesthetic decision as anything. If your project requirements don't limit you to specific languages for compatibility, dependency, or performance reasons, you might as well pick the one you feel the best about.
|
487,209 | 487,310 | Loop over variables in Lisp | I wrote the function
(defun test ()
(let ((str1 "foo") (str2 "bar"))
(loop for s in '(str1 str2) do (message s))))
but it does not work. The Elisp Backtrace message is:
Debugger entered--Lisp error: (wrong-type-argument stringp str1)
How can I make it work?
P.S.: the following modified version works perfectly, but I need the original version
(defun test1 ()
(loop for s in '("asdf" "fdsa") do (message s)))
| The quote operator (for which the apostrophe is syntactic sugar) means that its arguments are not evaluated, i.e. (quote (str1 str2)) returns a list of two symbols. Use list instead: (list str1 str2).
|
497,890 | 499,046 | Learning Clojure without Java Knowledge | Ok, so I'm psyched about another list. I got myself a copy of the beta Clojure programming book...
And the one thing I'm noticing most is that it's assumed I know... like all the major java classes.
Except, generally, I don't really care about Java. I just want enough knowledge of it for Clojure to be an option for me.
Any suggestion as to how to learn just what I need of it all?
| My main recommendation for you, you've already accomplished by buying Programming Clojure. I've avoided and loathed Java for years and years, and (Programming) Clojure rehabilitated it enough that the language now excites me. Who'd've thought that a famously onerous system would let you interactively (map #(.getName %) (.getMethods (class ""))) ? Look through "Working with Java, 3.5 Adding Ant Projects and Tasks to Lancet" for an exploration in a style that I'm familiar with from Ruby.
If you're in Freenode #clojure , also join ##java. Get Java's API documentation and keep it handy. Search the web for a Java answer to something you want to do and translate it more or less directly to Clojure.
EDIT: At clj:
user=> (use 'clojure.contrib.javadoc)
nil
user=> (keys (ns-publics 'clojure.contrib.javadoc))
(*remote-javadocs* javadoc find-javadoc-url add-remote-javadoc
*core-java-api* add-local-javadoc *local-javadocs*)
user=> (javadoc "this is a java.lang.String")
true (browses to http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html)
user=> (javadoc java.net.ServerSocket)
true (...)
user=>
|
500,026 | 500,448 | What is a good mathematically inclined book for a Lisp beginner? | I am looking for a mathematical book on Lisp. Some ideas?
| Structure and Interpretation of Computer Programs uses mathematical examples. It's not really a book for learning a particular version of Lisp, but you'll learn the concepts.
|
506,167 | 506,194 | Building a Texas Hold'em playing AI..from scratch | I'm interested in building a Texas Hold 'Em AI engine in Java. This is a long term project, one in which I plan to invest at least two years. I'm still at college, haven't build anything ambitious yet and wanting to tackle a problem that will hold my interest in the long term. I'm new to the field of AI. From my data structures class at college, I know basic building blocks like BFS and DFS, backtracking, DP, trees, graphs, etc. I'm learning regex, studying for the SCJP and the SCJD and I'll shortly take a (dense) statistics course.
Questions:
-Where do I get started? What books should I pick? What kind of AI do poker playing programs run on? What open source project can I take a page from? Any good AI resources in Java? I'm interested in learning Lisp as well, is Jatha good?
| The following may prove useful:
The University of Alberta Computer Poker Research Group
OpenHoldem
Poker Hand Recognition, Comparison, Enumeration, and Evaluation
The Theory of Poker
The Mathematics of Poker
SpecialKPokerEval
|
517,113 | 520,268 | Lisp grammar in yacc | I am trying to build a Lisp grammar. Easy, right? Apparently not.
I present these inputs and receive errors...
( 1 1)
23 23 23
ui ui
This is the grammar...
%%
sexpr: atom {printf("matched sexpr\n");}
| list
;
list: '(' members ')' {printf("matched list\n");}
| '('')' {printf("matched empty list\n");}
;
members: sexpr {printf("members 1\n");}
| sexpr members {printf("members 2\n");}
;
atom: ID {printf("ID\n");}
| NUM {printf("NUM\n");}
| STR {printf("STR\n");}
;
%%
As near as I can tell, I need a single non-terminal defined as a program, upon which the whole parse tree can hang. But I tried it and it didn't seem to work.
edit - this was my "top terminal" approach:
program: slist;
slist: slist sexpr | sexpr;
But it allows problems such as:
( 1 1
Edit2: The FLEX code is...
%{
#include <stdio.h>
#include "a.yacc.tab.h"
int linenumber;
extern int yylval;
%}
%%
\n { linenumber++; }
[0-9]+ { yylval = atoi(yytext); return NUM; }
\"[^\"\n]*\" { return STR; }
[a-zA-Z][a-zA-Z0-9]* { return ID; }
.
%%
An example of the over-matching...
(1 1 1)
NUM
matched sexpr
NUM
matched sexpr
NUM
matched sexpr
(1 1
NUM
matched sexpr
NUM
matched sexpr
What's the error here?
edit: The error was in the lexer.
| The error is really in the lexer. Your parentheses end up as the last "." in the lexer, and don't show up as parentheses in the parser.
Add rules like
\) { return RPAREN; }
\( { return LPAREN; }
to the lexer and change all occurences of '(', ')' to LPAREN and RPAREN respectively in the parser. (also, you need to #define LPAREN and RPAREN where you define your token list)
Note: I'm not sure about the syntax, could be the backslashes are wrong.
|
522,222 | 522,344 | Functional Programming in C# vs LISP | What are the primary differences between LISP and C# with regards to functional programming? In specific, if a LISP programmer was to switch to using C#, what are the features they are most likely to miss?
| Doing functional programming in C# is technically possible (well, any language that has function pointers or delegates equivalent can be "functional") -- but C# gets very very painful if you try to do much.
Off the top of my head, in no particular order:
Type inference
Only exists for locals now
Should apply to pretty much everything
The #1 problem I have with C# is this. Particularly when you declare a local function... Func<...> = ouch.
Full first class functions
Delegates aren't the answer, since they aren't structually equivalent. There's no canonical type to represent a function of a certain type. Ex: What is "increment"? Is it a Func? Is it a Converter? Is it something else? This in turn makes inference more complicated.
Automatic generalization
Sucks to have to calculate and specify all the generic type parameters and their constraints
Better support for immutability
Make it trivial to declare simple data types
Copy-with-modify type stuff (var x = oldX { SomeField = newVal })
Tuples C# 7
Discriminated unions (sum types)
Pattern matching C# 7
Makes tuples and sum types much more valuable
Allows more expression-oriented code
General monad syntax
Makes things like async code much easier to write C# 5
After you've nested 2+ layers of BeginXXX/EndXXX, it gets quite ugly.
Easy syntax for function blocks, so you don't end up with closing lines like "});});"
Edit: One more:
Function composition
Right now it's painful to do much of any sort of function composition. Currying, chaining, etc. LINQ doesn't get as hurt here because extension methods take the first parameter like an instance method.
C# should emit tail.call too. Not needed, the JIT will add tail calls itself as appropriate.
Items in bold have been addressed since this answer was written.
|
533,960 | 641,231 | How Do I Run Sutton and Barton's "Reinforcement Learning" Lisp Code? | I have been reading a lot about Reinforcement Learning lately, and I have found "Reinforcement Learning: An Introduction" to be an excellent guide. The author's helpfully provice source code for a lot of their worked examples.
Before I begin the question I should point out that my practical knowledge of lisp is minimal. I know the basic concepts and how it works, but I have never really used lisp in a meaningful way, so it is likely I am just doing something incredibly n00b-ish. :)
Also, the author states on his page that he will not answer questions about his code, so I did not contact him, and figured Stack Overflow would be a much better choice.
I have been trying to run the code on a linux machine, using both GNU's CLISP and SBCL but have not been able to run it. I keep getting a whole list of errors using either interpreter. In particular, most of the code appears to use a lot of utilities contained in a file 'utilities.lisp' which contains the lines
(defpackage :rss-utilities
(:use :common-lisp :ccl)
(:nicknames :ut))
(in-package :ut)
The :ccl seems to refer to some kind of Mac-based version of lisp, but I could not confirm this, it could just be some other package of code.
> * (load "utilities.lisp")
>
> debugger invoked on a
> SB-KERNEL:SIMPLE-PACKAGE-ERROR in
> thread #<THREAD "initial thread"
> RUNNING {100266AC51}>: The name
> "CCL" does not designate any package.
>
> Type HELP for debugger help, or
> (SB-EXT:QUIT) to exit from SBCL.
>
> restarts (invokable by number or by
> possibly-abbreviated name): 0:
> [ABORT] Exit debugger, returning to
> top level.
>
> (SB-INT:%FIND-PACKAGE-OR-LOSE "CCL")
I tried removing this particular piece (changing the line to
(:use :common-lisp)
but that just created more errors.
> ; in: LAMBDA NIL ; (+
> RSS-UTILITIES::*MENUBAR-BOTTOM* ;
> (/ (- RSS-UTILITIES::MAX-V
> RSS-UTILITIES::V-SIZE) 2)) ; ; caught
> WARNING: ; undefined variable:
> *MENUBAR-BOTTOM*
>
> ; (-
> RSS-UTILITIES::*SCREEN-HEIGHT*
> RSS-UTILITIES::*MENUBAR-BOTTOM*) ; ;
> caught WARNING: ; undefined
> variable: *SCREEN-HEIGHT*
>
> ; (IF RSS-UTILITIES::CONTAINER ;
> (RSS-UTILITIES::POINT-H ;
> (RSS-UTILITIES::VIEW-SIZE
> RSS-UTILITIES::CONTAINER)) ;
> RSS-UTILITIES::*SCREEN-WIDTH*) ; ;
> caught WARNING: ; undefined
> variable: *SCREEN-WIDTH*
>
> ; (RSS-UTILITIES::POINT-H
> (RSS-UTILITIES::VIEW-SIZE
> RSS-UTILITIES::VIEW)) ; ; caught
> STYLE-WARNING: ; undefined function:
> POINT-H
>
> ; (RSS-UTILITIES::POINT-V
> (RSS-UTILITIES::VIEW-SIZE
> RSS-UTILITIES::VIEW)) ; ; caught
> STYLE-WARNING: ; undefined function:
> POINT-V
Anybody got any idea how I can run this code? Am I just totally ignorant of all things lisp?
UPDATE [March 2009]: I installed Clozure, but was still not able to get the code to run.
At the CCL command prompt, the command
(load "utilities.lisp")
results in the following error output:
;Compiler warnings :
; In CENTER-VIEW: Undeclared free variable *SCREEN-HEIGHT*
; In CENTER-VIEW: Undeclared free variable *SCREEN-WIDTH*
; In CENTER-VIEW: Undeclared free variable *MENUBAR-BOTTOM* (2 references)
> Error: Undefined function RANDOM-STATE called with arguments (64497 9) .
> While executing: CCL::READ-DISPATCH, in process listener(1).
> Type :GO to continue, :POP to abort, :R for a list of available restarts.
> If continued: Retry applying RANDOM-STATE to (64497 9).
> Type :? for other options.
1 >
Unfortuately, I'm still learning about lisp, so while I have a sense that something is not fully defined, I do not really understand how to read these error messages.
| That code is for Macintosh Common Lisp (MCL). It will only run there. Using Clozure CL (CCL) will not help. You would have to comment the graphics code. The random state stuff also is slightly special for MCL. You have to port it to portable Common Lisp (make-random-state, etc.). Also the file names are special for the Mac.
Clozure CL is a fork from Macintosh Common Lisp, but has be changed to Unix conventions (pathnames, ...) and does not include the special graphics code of MCL.
|
535,277 | 535,284 | The Clojure (or Lisp) Equivalent of a Compound Boolean Test | In C++ I'd write something like this:
if (a == something && b == anotherthing)
{
foo();
}
Am I correct in thinking the Clojure equivalent is something like this:
(if (= a something)
(if (= b anotherthing)
(foo)))
Or is there another way to perform a logical "and" that I've missed? As I said the latter form seems to work correctly--I was just wondering if there's some simpler way to perform the logical and. And searching for "boolean" "logical" and "and" on the Clojure Google Group turned up too many results to be much use.
| In Common Lisp and Scheme
(and (= a something) (= b another) (foo))
|
541,407 | 541,522 | Lisp Code Formatting | One of the people who took the time to comment on my other question about Clojure/LISP syntax pointed out that I had not written my sample code in the standard LISP way. So he was kind enough to rewrite the code snippet and that's a big help. But it raised another question in my mind. Why would this:
(if (= a something)
(if (= b otherthing)
(foo)))
which is standard LISP formatting be preferrable to this form:
(if (= a something)
(if (= b otherthing)
(foo)
)
)
which is the way I would have naively formatted this code because of my C++ development background. I'm wondering if there's any benefit to the latter formatting or it's just an entrenched standard (like a QWERTY keyboard). I'm not trying to be argumentative--it's just difficult for me to understand why the first form would be preferable. The second form helps me to see the code structure more easily.
| The closing parentheses on extra lines don't really help with seeing the structure of the code, because you can get the same information from the level of indentation. However, the second form takes up almost twice as many lines, forcing you to scroll more often when reading code.
And if you need to inspect the nested parentheses more closely, an editor that highlights the matching parenthesis will help you. This will also be easier when the matching parenthesis is not too far away.
If expressions get too long and complicated to be easily read, it may also be a sign that you should extract part of the functionality into a separate function.
|
543,579 | 543,661 | What is the most impressive Lisp application? | I know that this is subjective and all, but still, can you provide some list of serious applications that were written in Lisp (perhaps along with what Lisp it is)?
| ITA Software's airline-fare search service. See here to understand why this is impressive.
|
553,281 | 553,506 | What is wrong with the following Common Lisp macro using gensym? | Learning Common Lisp (using GNU CLISP 2.43) .. so might be a noob mistake. Example is the 'print prime numbers between x and y'
(defun is-prime (n)
(if (< n 2) (return-from is-prime NIL))
(do ((i 2 (1+ i)))
((= i n) T)
(if (= (mod n i) 0)
(return NIL))))
(defun next-prime-after (n)
(do ((i (1+ n) (1+ i)))
((is-prime i) i)))
(defmacro do-primes-v2 ((var start end) &body body)
`(do ((,var (if (is-prime ,start)
,start
(next-prime-after ,start))
(next-prime-after ,var)))
((> ,var ,end))
,@body))
(defmacro do-primes-v3 ((var start end) &body body)
(let ((loop-start (gensym))
(loop-end (gensym)))
`(do ((,loop-start ,start)
(,loop-end ,end)
(,var (if (is-prime ,loop-start)
,loop-start
(next-prime-after ,loop-start))
(next-prime-after ,var)))
((> ,var ,loop-end))
,@body )))
do-primes-v2 works perfectly.
[13]> (do-primes-v2 (p 10 25) (format t "~d " p))
11 13 17 19 23
Next I tried using gensym to avoid naming clashes in macro expansion - do-primes-v3. However I'm stuck with a
*** - EVAL: variable #:G3498 has no value
Tried using macro-expand to see if i could spot the mistake but I can't.
[16]> (macroexpand-1 `(do-primes-v3 (p 10 25) (format t "~d " p)))
(DO
((#:G3502 10) (#:G3503 25)
(P (IF (IS-PRIME #:G3502) #:G3502 (NEXT-PRIME-AFTER #:G3502))
(NEXT-PRIME-AFTER P)))
((> P #:G3503)) (FORMAT T "~d " P)) ;
| Use DO* instead of DO.
DO Initializes the bindings in a scope where they are not yet visible. DO* initializes the bindings in a scope where they are visible.
In this particular case var needs to reference the other binding loop-start.
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 28