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,295,763 | 1,298,639 | (emulated) Macros in Haskell? | A person on Reddit has brought this code to my attention:
main = do
let ns = [print 1, print 2, print 3]
sequence_ ns
sequence_ $ reverse ns
sequence_ $ tail ns ++ [head ns]
head ns
What's going on here is we have an array of operations that we can do stuff with, like reverse or get its tail or head.
Awesome... | It is a bit more complicated than in Lisp, but for metaprogramming in Haskell, you can use Template Haskell.
E.g., [|print 1|] will be translated to
return $ AppE (VarE $ mkName "print") (LitE $ IntegerL 1)
which has the type Q Exp (a quotation of an expression).
If you want to splice your own data into a quotation, [... |
1,303,680 | 1,327,979 | Do you have a mnemonic for remembering the meaning of car and cdr? | Most of my Lisp experience comes from Elisp. As such, I find myself writing Lisp only on occasion. By the time I come back to it, I often forget the difference between car and cdr and need to reference the docs to jog my memory.
What kinds of clever mnemonics do you use to remember the difference between Lisp funct... | Of the two words car and cdr, car is the one I've heard first.
|
1,307,567 | 1,307,648 | Eval not working on unexpanded macro quote | In common lisp I can do this:
src-> (defmacro macro-hello ()
`"hello")
(eval '(macro-hello))
no problem.
In clojure:
(defmacro macro-hello []
`"hello")
(eval '(macro-hello))
gives me an error. Have I done something wrong?
Clojure Error:
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: mac... | Your code works for me.
user> (defmacro macro-hello [] `"hello")
#'user/macro-hello
user> (eval '(macro-hello))
"hello"
This is via bleeding-edge Clojure. "Unable to resolve symbol" means it can't find the macro called macro-hello in the current namespace. Are you running this from the REPL or in a source file? I ty... |
1,310,783 | 1,310,849 | How to read input until EOF in Lisp | How do I read an input stream until EOF in Lisp? In C, you might do it like this:
while ((c = getchar()) != EOF)
{
// Loop body...
}
I would like to be able to pipe data to my Lisp programs without having to specify the data size in advance. Here's an example from something I'm doing now:
(dotimes (i *n*)
(... | read-line takes an optional argument (eof-error-p) allowing it to return either NIL (default) or a user-specified value (eof-value) on hitting an EOF, instead of signalling an error.
From Chapter 19 of Successful Lisp:
READ-LINE &optional stream eof-error-p eof-value recursive-p
In the read functions listed above, opt... |
1,313,585 | 1,314,456 | CLSQL symbol exports | Does anyone know about how the clsql-sys methods get exported to the clsql-sys/cl-user package?
The methods are defined individually for each database type.
For example, suppose I define a method in db-mysql/mysql-sql.lisp in package clsql-mysql:
(defpackage #:clsql-mysql
(:use #:common-lisp #:clsql-sys #:mysql #:clsql... | I guess what you mean is the exports list in mysql-package.lisp.
|
1,317,023 | 1,317,039 | What is the Definition of a Lisp Cons Cell? | What exactly is the definition of a Common Lisp Cons Cell? How is a Cons Cell different than a standard linked list item? After all, both the cons cell and the linked list item have a value and a pointer to the next cell or item... or is this understanding wrong?
| Cons cells in general hold two pointers that can point to anything. General usage of course is to point to a "value" with the left one, and to another Cons cell (or nil) with the "right" one.
|
1,318,729 | 1,318,751 | What Lisp is better at parsing? | I'd like to implement a Lisp interpreter in a Lisp dialect mainly as a learning exercise. The one thing I'm thrown off by is just how many choices there are in this area. Primarily, I'm a bit more interested in learning about some of the Lisps that have been around a while (like Scheme or Common Lisp). I don't want ... | There are some books about that:
SICP chapter 4 and 5
PAIP, chapter 5
LiSP, the whole book explains implementing Lisp
Anatomy of Lisp, old classic about implementing Lisp
All of the above books are highly recommended, though Anatomy of Lisp is oldish, hard to get and hard to read.
Both Scheme and Common Lisp are fine... |
1,351,956 | 1,352,082 | Read macros: what do you use them for? | I'm trying to get a feel for the parts of Lisp that I haven't used very much up to now. Read macros have caught my attention at the moment. There isn't a huge amount of info about their use and it would help to see what people have done with them, both to get examples of how they work and also to see what sorts of prob... | S-expressions are Lisp's syntax for Lisp data. S-expressions are read with the function READ and read macros are Lisp's built-in way to extend the reader. This means that the most direct use of read macros is to implement the pre-defined data syntax and open up possibilities to change or extend the way Lisp reads s-exp... |
1,360,562 | 1,360,577 | Lisp void-variable error when evaluating function | I'm trying to learn Lisp (elisp, actually), and I tried writing the following function as an exercise Project Euler Problem 2
(defun sumfib (n fn1 fn2 sum)
"Calculate Fibonacci numbers up to 4,000,000 and sum all the even ones"
(if (< 4000000 (+ fn1 fn2))
sum
(if (equal n 3)
(sumfib 1 (+ fn1 fn2) ... | Not sure if this solves your problem (I don't have an elisp interpreter handy), but you're missing a right paren. There should be one at the end of the first 'if' statement, after 'sum'.
(if (< 4000000 (+ fn1 fn2))
sum)
instead of:
(if (< 4000000 (+ fn1 fn2))
sum
I also think there might be some other... |
1,371,243 | 1,380,864 | which clojure library interface design is best? | I want to provide multiple implementations of a message reader/writer. What is the best approach?
Here is some pseudo-code of what I'm currently thinking:
just have a set of functions that all implementations must provide and leave it up to the caller to hold onto the right streams
(ns x-format)
(read-message [stream]... | I think the first option is better. It's more extensible, depending how these objects are going to be used. It's easier to add or change a new function that works on an existing object if the functions and objects are separate. In Clojure there usually isn't much reason to bundle functions along with the objects th... |
1,385,197 | 1,385,216 | Lisp warning: xx is neither declared nor bound, it will be treated as if it were declared SPECIAL | I am new to lisp and am writing a few simple programs to get more familiar with it. One of the things I am doing is writing a recursive and iterative version of a factorial method. However, I have come across a problem and can't seem to solve it.
I saw a similar error at
Lisp: CHAR is neither declared nor bound
but ... | You need to bind the variable 'result' - using 'let', for example - before starting to use it:
(defun it-fact(num)
(let ((result 1))
(dotimes (i num)
(setf result (* result (+ i 1))))))
For futher details you might want to read this ...
|
1,398,014 | 1,398,699 | Simple issue with subseq (LISP) | I just started using LISP, coming from a background in C. So far its been fun, although with an incredible learning curve (I'm an emacs newbie too).
Anyway, I'm having a silly issue with the following code to parse include statements from c source - if anyone can comment on this and suggest a solution, it would help a ... | (defun include-start (line)
"returns the string position after the '#include ' directive or nil if none"
(let ((search-string "#include "))
(when (search search-string line)
(length search-string))))
(defun get-include (line)
(let ((s (include-start line)))
(when s
(subseq line s))))
|
1,403,717 | 1,403,758 | How do I iterate through a directory in Common Lisp? | I'm using OpenMCL on Darwin, and I'd like to do something like:
(loop for f in (directory "somedir")
collect (some-per-file-processing f))
But I can't get directory to return anything other than NIL, and I can't seem to find any good explanation online (other than "its different for each system").
Any pointers?
| Does your pathname specification contain a wildcard? Common Lisp's pathname stuff is somewhat hard to grasp at first - at least for me it was... As the CLHS states on the directory function:
If the pathspec is not wild, the
resulting list will contain either
zero or one elements.
In order to have your pathname in... |
1,409,069 | 1,409,102 | Using string object as a hash key in Common Lisp | I'm trying to create a "dictionary" type - ie hash table with a string as a key. Is this possible or wise in Lisp?
I noticed that this works as expected:
> (setq table (make-hash-table))
#<HASH-TABLE :TEST EQL size 0/60 #x91AFA46>
> (setf (gethash 1 table) "one")
"one"
> (gethash 1 table)
"one"
However, the following ... | You need to make hash-table that uses 'equal instead if 'eql. 'eql doesn't evaluate two strings with same content to 't, while 'equal does.
Here is how you do it:
(make-hash-table :test 'equal)
As skypher noted you can also use 'equalp instead if you want case-insensitive string hashing.
|
1,412,981 | 1,413,062 | Is Clojure closer to Scheme or Common Lisp from a beginner's perspective? | If I want to learn Clojure, should I start by learning Scheme or Common Lisp?
Or is Clojure different enough from both of these, that I should just start learning Clojure by itself?
| It would be to your benefit to learn all three, if only so you can pick which one is best for your needs. All three have their own strengths and weaknesses.
Clojure is vaguely like Scheme in that it's a mostly-functional language and is a Lisp1. Clojure also borrows things from Common Lisp, like multimethods and macr... |
1,413,390 | 1,413,521 | Why Clojure over other JVM Lisps: Kawa, Armed Bear or SISC? | The JVM already had three Lisps before Clojure arrived on the scene: Kawa, Armed Bear and SISC.
What gap does Clojure fill that was left by those Lisps?
| Kawa, ABCL, and SISC are reimplementations of existing languages that are quite long in the tooth. They are excellent if for some reason you want to use standard Scheme or standard Common Lisp on the JVM.
Clojure is a new language. It doesn't fill a gap. It adds entirely new possibilities. It favors a purely functional... |
1,417,266 | 1,417,293 | What is the difference between '(a b c) and (list 'a 'b 'c)? | I am reading "On lisp" and encountered this code (I simplified it a bit).
CL-USER> (defun foo ()
'(a b c))
FOO
CL-USER> (foo)
(A B C) ... | The call to LIST creates a new list each time it is evaluated. The list literal might be placed in a read-only memory segment after compilation. A destructive update on the lists with NCONC is then problematic, possibly with undefined consequences (segmentation error, changing the literal for future references, or not... |
1,422,735 | 1,422,798 | LISP: multi-level recursive reverse function | How to reverse a list such that every sublist is also reversed? This is what I have so far:
(defun REV (L)
(cond
((null L) nil)
((listp L)
(append
(REV (cdr L))
(list (car L))))
(t
(append
(REV (cdr L))
(list (car L))))))
| You are on the right track, but your last two conditions have the same action, which should give an indication that one of them is not doing what it should. Indeed, the second condition, the listp case, is not right, because when it's a list, you need to append the reverse of that list instead of the unmodified list. A... |
1,436,573 | 1,446,667 | In CL Postmodern what :col-type to use for Many to Many field? | When defining a database access object for use in cl-postmodern, what should the :col-type be for a Many to Many field?
| The answer is that there is no :col-type for a ManyToMany field (as in Django) because a many to many relationship is implemented by creating a new table which is what must be referenced by Postmodern. This is part of the object relational magic which Postmodern doesn't supply.
|
1,450,734 | 1,450,776 | scheme list equivalence comparison | Hello I need to check if two lists have same elements in same order but I wasn't able to achieve as it seems like scheme eq? and eqv? checks by reference so giving false to such:
> (eq? (list 1 2 3) (list 1 2 3))
#f
> (eqv? (list 1 2 3) (list 1 2 3))
#f
How to achieve this ?
| This site explains the difference between those operators. But essentially, you want to use equal? when you want to compare the contents of two objects.
|
1,451,304 | 1,451,334 | Python generators in various languages | How do you emulate Python style generators in your favorite language? I found this one in Scheme. It must be interesting to see other implementations, especially in those languages that don't have first-class continuations.
| Here is an example in C++ that simulates generators using fibers:
Yield Return Iterator for Native C++ Using Fibers
The "yield return" iterator is a
language feature that was created for
one reason: simplicity. It is
generally much easier to iterate
across whole collectionl, storing all
context needed in loc... |
1,453,588 | 1,453,629 | How do I tell if the value of a variable is a symbol bound to a procedure in Scheme? | I am familiar with Common Lisp and trying to learn some Scheme, so I have been trying to understand how I'd use Scheme for things I usually code in Common Lisp.
In Common Lisp there's fboundp, which tells me if a symbol (the value of a variable) is bound to a function. So, I would do this:
(let ((s (read)))
(if (fbou... | This way?
check if it is a symbol
evaluate the symbol using EVAL to get its value
check if the result is a procedure with PROCEDURE?
|
1,459,429 | 1,461,234 | strtotime for Emacs Lisp | Is there any functionality in Emacs Lisp that behaves similar to PHP's strtotime function? (Actually AFAIK it implements relative items of the GNU date input formats.)
In PHP I can write
echo strtotime("+2 months"); //1258891352
echo strtotime("-3 months +2 weeks"); //1246952239
which return the corresponding UNIX tim... | While not exactly what you're asking for, this may be of use. There's a command 'org-schedule in the package org-mode that has a really nice interface to choosing dates. The specific command that does it is 'org-read-date, which understands many ways of representing the date, including:
+0 --> today
. ... |
1,481,053 | 1,481,132 | What is the exact definition of a Metacircular Interpreter? | Is it legal to call a C compiler written in C or a PHP interpreter written in PHP metacircular? Is this definition valid only for languages of a specific type, like Lisp? In short, what are the conditions that an interpreter should satisfy for being called Metacircular?
| A metacircular interpreter is an interpreter written in a (possibly more basic) implementation of the same language. This is usually done to experiment with adding new features to a language, or creating a different dialect.
The reason this process is associated with Lisp is because of the highly lucid paper "The Art o... |
1,484,335 | 1,484,376 | In common-lisp, how do I modify part of a list parameter from within a function without changing the original list? | I'm trying to pass a list to a function in Lisp, and change the contents of that list within the function without affecting the original list. I've read that Lisp is pass-by-value, and it's true, but there is something else going on that I don't quite understand. For example, this code works as expected:
(defun test ()... | SETF modifies a place. n can be a place. The first element of the list n points to can also be a place.
In both cases, the list held by original is passed to modify as its parameter n. This means that both original in the function test and n in the function modify now hold the same list, which means that both origin... |
1,490,798 | 1,490,845 | Function Table in Scheme using Association List | I am attempting to build a rudimentary interpreter in Scheme, and I want to use an association list to map to arithmetic functions. This is what i have so far:
; A data type defining an abstract binary operation
(define binoptable
'(("+" . (+ x y)))
("-" . (- x y))
("*" . (* x y))
("/" . (/ x y)))
)
The ... | You probably want:
(define binoptable
`(("+" . ,+)
("-" . ,-)
("*" . ,*)
("/" . ,/)))
Also, you can use a macro to make it easier to specify:
(define-syntax make-binops
(syntax-rules ()
[(make-binops op ...)
(list (cons (symbol->string 'op) op) ...)]))
(define binoptable (make-binops + - * /))... |
1,495,475 | 1,495,514 | Parsing numbers from strings in lisp | Here's the brief problem:
Input: a list of strings, each containing numbers
(" 3.4 5.4 1.2 6.4" "7.8 5.6 4.3" "1.2 3.2 5.4")
Output: a list of numbers
(3.4 5.4 1.2 6.4 7.8 5.6 4.3 1.2 3.2 5.4)
Here's my attempt at coding this:
(defun parse-string-to-float (line &optional (start 0))
"Parses a list of floats out of ... | This is not a task you want to be doing recursively to begin with. Instead, use LOOP and a COLLECT clause. For example:
(defun parse-string-to-floats (line)
(loop
:with n := (length line)
:for pos := 0 :then chars
:while (< pos n)
:for (float chars) := (multiple-value-list
(read-from-strin... |
1,509,051 | 1,512,557 | How can I send a file in a POST request? | I'm building a clojure API to my website that is basically a wrapper around the original web API. One of the features that I'm not being able to implement is file sending via POST requests, basically what I would do in shell with curl -F foo=bar baz=@bak.jpg foobar.com.
I'm using clojure-http-client, and initially trie... | Try using clojure-apache-http, a Clojure wrapper for the full-featured Apache HTTP libraries. It does support multipart/form-data POST.
|
1,511,812 | 1,511,915 | Hex to decimal conversion in common lisp | Is there an easy helper function in common lisp to convert from hex to decimal?
| (parse-integer "ff" :radix 16)
|
1,511,981 | 1,512,395 | How to examine list of defined functions from Common Lisp REPL prompt | I'm evaluating/testing a browser based application presumably written in common lisp. Apart from the browser based interface, the software provides a 'Listener' window with a 'CL-User >' REPL prompt.
I wish to examine the list of functions, symbols, and packages from the REPL prompt. So that I could co-relate the fron... | If you don't know what symbols you're looking for, but do know what packages you want to search, you can drastically reduce the amount of searching you have to do by only listing the symbols from those specific packages:
(defun get-all-symbols (&optional package)
(let ((lst ())
(package (find-package package)... |
1,514,331 | 1,514,540 | Convert a lisp string to stream | I have a file that looks like this:
A B C D E
0 8 6 12 5
8 0 10 8 9
6 10 0 7 11
12 8 7 0 6
5 9 11 6 0
I don't know ahead of time how many rows and columns there will be. I would like to read the top line, which will let me know the number of rows to expect . I found lisp's (read <stream>) function which, in a loop, ca... | You can either use the string as a stream by using the with-input-from-string macro, or use read-from-string in a loop. You may also be interested in the read-delimited-list function, although you would have to add some kind of delimiter character to the end of the string before using it.
|
1,518,933 | 1,520,833 | Image Processing, extending JPanel and Simulating Classes in Clojure | there! I'm building an image-processing application in swing/clojure, and right now I need to develop an image panel in which I can click and compute data. Thanks to coobird, I now have a good idea on how to do it in Java, but I still don't get many issues on its integration with Clojure.
Let's take a look at how coobi... |
proxy actually creates an instance tada! You don't need to create a constructor.
Yes, but consider using a clojure ref instead. Also using def like that on the second last line is nasty! it creates a global binding for point-clicked when your logic relies on the lexically scoped one created by let.
(proxy-super paintC... |
1,522,724 | 1,522,755 | Are there ruby equivalents to car, cdr, and cons? | Are there ruby equivalents to the lisp car, cdr, and cons functions? For those unfamiliar with lisp, here's what I want from ruby:
[1,2,3].car => 1
[1,2,3].cdr => [2,3]
[2,3].cons(1) => [1,2,3]
(in lisp):
(car '(1 2 3)) => 1
(cdr '(1 2 3)) => (2 3)
(cons 1 '(2 3)) => (1 2 3)
| Ruby arrays are not implemented as singly-linked lists, so it is not as useful to have car and cdr and stuff.
If you really wanted, you could do
[1,2,3][0] => 1
[1,2,3].first => 1
[1,2,3][1..-1] => [2,3]
[1] + [2,3] => [1,2,3]
|
1,527,548 | 1,527,720 | Why does Clojure have "keywords" in addition to "symbols"? | I have a passing knowledge of other Lisps (particularly Scheme) from way back. Recently I've been reading about Clojure. I see that it has both "symbols" and "keywords". Symbols I'm familiar with, but not with keywords.
Do other Lisps have keywords? How are keywords different from symbols other than having different no... | Here's the Clojure documentation for Keywords and Symbols.
Keywords are symbolic identifiers that evaluate to themselves. They provide very fast equality tests...
Symbols are identifiers that are normally used to refer to something else. They can be used in program forms to refer to function parameters, let bindings, ... |
1,539,144 | 1,539,175 | What is ' (apostrophe) in Lisp / Scheme? | I am on day 1 hour 1 of teaching myself Scheme. Needless to say, I don't understand anything. So I'm reading The Little Schemer and using this thing:
http://sisc-scheme.org/sisc-online.php
as an interpreter.
I need to use ' in for example
(atom? 'turkey)
to avoid an "undefined variable" error. The ', according to... | The form 'foo is simply a faster way to type the special form
(quote foo)
which is to say, "do not evaluate the name foo replacing it with its value; I really mean the name foo itself".
I think SISC is perfectly fine for exploring the exercises in TLS.
|
1,542,551 | 1,542,769 | binding local variables in python | I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a bit much.
So what I had in mind was so... | I can only second Lennart and Daniel - Python is not Lisp, and trying to write language X into language Y is usually inefficient and frustrating at best.
First point: your example code
data = [1,2,3]
output = ((lambda x: x + x)
(data[2]))
would be much more readable as:
data = [1, 2, 3]
output = (lambda x=da... |
1,548,605 | 1,548,994 | Emacs lisp "shell-command-on-region" | In GNU Emacs, I want to run a program, figlet, on the currently selected text. I then want to comment the region which is produced.
I have figured out how to do it using the standard Emacs commands:
set mark with C-<space> at the start of the word
move cursor to the end of the word
C-u M-x shell-command-on-region RET ... | I'm unsure what you're trying to accomplish with the pushing and popping of the marks, I believe you'd get the same functionality by doing this:
(defun figlet-region (&optional b e)
(interactive "r")
(shell-command-on-region b e "figlet")
(comment-region b e))
The argument to interactive tells Emacs to pass the... |
1,559,701 | 1,559,919 | CMS in functional programming language | Are there any CMS'es, written in functonal programming languages (lisp, haskell, f#/nemerle, scala, erlang, clojure, smalltalk) already?
| In OCaml:
COCANWIKI
ocsimore
|
1,560,174 | 1,562,121 | Do languages with meta-linguistic abstraction perform better than those that just use reflection API for that? | Say, if I have a Lisp program, which uses (eval 'sym) and looks it up in its symbol-table does it actually perform better than something like aClass.getField("sym", anInstance) in "static" languages?
| In general (modulo implementation issues like bytecode vs native code or code generation quality), languages with metalinguistic abstraction provide more power to create programs that outperform programs that can be created in comparable timeframe with language that lacks such abstractions. The case is that when you wr... |
1,563,843 | 1,563,923 | Lisp Recursion Not Calling Previous Functions | I'm trying to have a function compare the first argument of a passed in argument to a value, then if it is true, perform some function, then recursively call the same function.
(defun function (expression)
(cond
((equal (first expression) "+")
(progn (print "addition")
(function (rest expression)... | Perhaps you mean to say:
(defun function (expression)
(cond (expression
(cond (equal (first expression) "+")
(print "addition")))
(function (rest expression)))))
the original recurses only if (first expression) is "+"
and also fails to do a nil-check.
|
1,569,999 | 1,570,012 | Lisp Append Not Working Properly | Hi I am trying append a simple element to a lisp list.
(append queue1 (pop stack1))
I thought the above code would append the first element of stack1 to queue1. Does queue1 need to be non nil? Thanks.
| Append returns the concatenated list (queue1 with the first element of stack1 appended). It does not modify queue1.
The destructive equivalent of append is nconc: this appends to the list "in place."
|
1,583,597 | 1,612,574 | asm / C / Python / Perl / Lisp / Scheme Programmer looking for something new to learn | I need to have an at-home project now that I'm working on Python/Django at work. I'd like to learn something new, so I was thinking of checking out Java.
What's the most well respected web framework for deploying Java web apps?
The only reason I'm not checking out ruby on rails is because of how similar the ORM and oth... | Sounds like you're into web programming, so smalltalk/seaside is a great one. IMO everyone should learn smalltalk even if they never use it, and seaside is a really different web framework than what you are used to. Django, fer instance, is all about REST, while the seaside philosophy basically says "to hell with REST.... |
1,597,355 | 1,597,387 | Why are parenscript functions changed to all lowercase? | When using parenscript if I execute
(parenscript:ps
(slot-value ($ "#mytextarea") 'selectionStart))
It produces the javascript
$('#mytextarea').selectionstart;
Note that selectionStart is now selectionstart. It lost the uppercase S on the Start!
How do I keep that uppercase S around?
| Parenscript will automatically convert from the lisp naming convention (dashes separating words) to CamelCase, so:
(parenscript:ps
(slot-value ($ "#mytextarea") 'selection-start))
results in
"$('#mytextarea').selectionStart;"
|
1,616,592 | 1,626,222 | Mathematica: Unevaluated vs Defer vs Hold vs HoldForm vs HoldAllComplete vs etc etc | I'm bewildered by all the built-in Mathematica functions that purport to prevent evaluation in some way: Unevaluated, Defer, Hold, and over half a dozen of the form Hold*. The Mathematica documentation just explains each function in isolation without explaining why you would choose one or the other. Can anyone offer ... | These are pretty tricky constructs, and it's tough to give clear explanations; they aren't as straightforward as Lisp macros (or, for that matter, the relationship between Lisp's QUOTE and EVAL). However, there's a good, lengthy discussion available in the form of notes from Robby Villegas's 1999 talk "Unevaluated Exp... |
1,623,259 | 1,624,499 | "unfold" for common lisp? | I learned quite a bit of scheme from SICP but am more interested in common lisp now. I know common lisp's fold is reduce, with special arguments for left or right folding, but what is the equivalent of unfold? Googling has not helped much. In fact I get the impression there is no unfold???
| Common Lisp has (loop ... collect ...). Compare
(loop for x from 1 to 10 collect (* x x))
with its equivalence using unfold:
(unfold (lambda (x) (> x 10))
(lambda (x) (* x x))
(lambda (x) (+ x 1))
1)
In general, (unfold p f g seed) is basically
(loop for x = seed then (g x) until (p x) collect (f x))
Edit:... |
1,626,104 | 1,626,126 | What does this xkcd code do? | On the xkcd site today, the following appeared as a joke in a <script language="scheme"> tag
so what does the following code do / represent?
(define
(eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp)
(lookup-variable-value exp env))
((quoted? exp)
(text-of-quotation exp))
((a... | It's essentially a simple interpreter, if you assume that all the requisite methods are filled in.
|
1,626,567 | 1,626,593 | Common Lisp: Beginner's trouble with funcall | I'm trying to pass a function as an argument and call that function within another function.
A piece of my code looks like this:
(defun getmove(strategy player board printflag)
(setq move (funcall strategy player board))
(if printflag
(printboard board))
strategy is passed as a symbol represented in a two dimensio... | Is strategy a variable with a functional value? If not, then use the #' syntax macro before it, i.e. #'strategy, or just (if the function is global) 'strategy.
WHY? Because arguments of a funcall call are evaluated. And your strategy symbol is just a variable name in this case. Variable this value 'RANDOMSTRATEGY. But ... |
1,630,352 | 30,791,107 | picoLisp language: onOff question | This question is really moot, I think I must have hit a bug in my program or something. If you are still looking for PicoLisp and onOff behaviour, look here.
is this supposed to happen?
: (show NIL)
NIL NIL
-> NIL
: (onOff)
-> T
: (show NIL)
T T
-> T
: (=T NIL)
-> T
:
(onOff sym ..) -> flg
Logical negates the VA... | This was a red herring, there was no bug. Sorry, HN wrong call. Also, it is now under the MIT (X11) license, the most liberal of open source licenses.
|
1,636,336 | 1,637,128 | something confusing about define-key (and the issue of when to quote an argument) | It seems one is not supposed to quote KEYMAP when using define-key.
(define-key org-remember-mode-map "\C-c\C-r" 'org-remember-kill)
I'm confused because I think that all arguments of a function that is not quoted are evaluated, and according to the help, define-key is a function, not a macro. I don't see why the valu... | You aren't actually changing what 'org-remember-map is (a pointer to a particular list structure), you are modifying the actual structure. Read this info page for details on modifying lists.
Specificially, if you take a look at the documentation for 'make-keymap:
(make-keymap &optional string)
Construct and return a ... |
1,645,008 | 1,645,149 | Calling Lisp from Ruby/Rails? | How might you call a Lisp program from a Rails application?... For example, allow the end user to enter a block of text in the Rails web app, have the text processed by the Lisp program and return results to the Rails app?
| Another simple way is to have Lisp running a HTTP server and contact Lisp from the outside via HTTP requests.
|
1,659,413 | 1,661,199 | Multiple constructors in common lisp | Can classes have multiple constructors and/or copy constructors in common-lisp? That is - in order to create a class for a new vector - "vecr" to represent 3-d vectors of real numbers, I'd like to define the new class that can be initialized in multiple ways:
(vecr 1.2) ==> #(1.2 1.2 1.2)
or
(vecr 1.2 1.4 3.2) ==> #(1... | I can't figure out how to comment on what was said above:
This function works well to create a
default #(0.0 0.0 0.0) type of vector.
However, (vecr 1.0) ==> #(1.0 0.0 0.0)
instead of the intended #(1.0 1.0
1.0). I suppose the way around this is to check whether all three were
passed, or just one of the opti... |
1,670,127 | 1,670,355 | Compiled dynamic language | I search for a programming language for which a compiler exists and that supports self modifying code. I’ve heared that Lisp supports these features, but I was wondering if there is a more C/C++/D-Like language with these features.
To clarify what I mean:
I want to be able to have in some way access to the programms co... | Probably there is a reason Lisp is like it is? Lisp was designed to program other languages and to compute with symbolic representations of code and data. The boundary between code and data is no longer there. This influences the design AND the implementation of a programming language.
Lisp has got its syntactical feat... |
1,675,322 | 1,675,835 | lisp file pointers in classes | I'm running up against a problem in understanding the CLOS way of handling file access within a class. In c++ I would be able to do this:
class Foo {
Foo (string filename); // opens the file (my_file) requested by the filename
~Foo (); // close the file
FILE * my_file; // a persistent file-handle
DataSt... | One option is to have the stream as a slot instead of the filename, and then scope it with WITH-OPEN-FILE:
(with-open-file (stream file)
(let ((foo (make-instance 'foo :stream stream)))
(frob foo)
(...other processing of foo...)))
Then your stream will be closed automatically.
|
1,678,449 | 1,683,528 | Using Lisp to reprint a list | I have a small and interesting problem,but I cannot come with a perfect solution,I would be grateful if you could help me or give me a hint on this.
The problem is :
given any list ,say like '(a b c),we will convert it to '[a b c]
or '(a (b c)) ,we will convert to '[A [B C]]
In other words,the function should do the sa... | Here's my take:
(defun bprint (object)
(typecase object
(cons
(write-char #\[)
(do ((list object (rest list)))
((endp list) (write-char #\]))
(bprint (first list))
(when (rest list)
(write-char #\Space))))
(t
(prin1 object)))
t)
That is: when encountering a li... |
1,683,107 | 1,692,526 | When is an initform used? | I'm forming a class for some work on molecular dynamics as follows:
(defclass %atom (particle)
((name :initarg :name :initform (error "Every atom in the system must have a name!"))
(mass :accessor mass :initarg :mass :initform (getmass name))
(charge :accessor charge :initarg :charge :initform (getcharge name))... | Usually one would use :initform to give a slot some default value. With defclass one can't compute initforms simply based on other slots. There are also other complications, so :initform should be used for simple forms.
Examples
set the z slot of a 3d-vector object to 0.0
set the list of windows in a screen object to ... |
1,692,656 | 1,692,671 | Common Lisp: cons inside loop | I wonder why in the following code, d is not being consed into x.
Any hints are much appreciated.
(defun it (x)
(setq f '(a b c))
(dolist (d f)
(cons d x))
(print x))
Thank you!
| I don't know a lot about LISP, but here's a few things I think I know that might help you:
(cons d x) doesn't put d "into" x; it creates a new value that consists of d, followed by the contents of x. If x is a list, then (cons d x) will also be a list.
(cons d x) doesn't change anything; it creates a value, but if you... |
1,695,351 | 1,695,473 | SICP 1.31: Approximating Pi | I'm working through SICP on my own, so I don't have an instructor to ask about this. This code is supposed to approximate pi but always returns zero instead.
(define (approx-pi acc)
(define (factors a)
(define basic-num
(if (= (mod a 2) 0)
(/ a 2)
(/ (- a 1) 2)))
(if (= (mod... | Your product function has a subtle flaw:
(product + 4 5)
returns 120 when the correct answer is 20.
The reason is
(product-iter 1 1) should be (product-iter lo 1)
|
1,712,604 | 1,712,628 | Easy ways to try out and test Lisp syntax? | Clojure has introduced me to the concept of Lisp syntax, and I'm interested, but it's a pain to get the Clojure repl set up and use it on different machines. What other resources are there out there for actually on-the-fly testing and playing with Lisp syntax?
I'm imagining something like a website where you can inp... | The SISC Online REPL is exactly what you need. It accepts Scheme syntax, which is a variant of Lisp.
For a standalone app I like PLT Scheme because it seems to work the same on every platform I've tried. I was previously using MIT Scheme on Ubuntu, but decided to switch when I bought a new machine with 64-bit Vista i... |
1,713,394 | 1,713,532 | Picolisp question, segfault when manipulating lists of numbers (from mailing list) | I'm new to Picolisp.
I tried this, and obtained a segfault:
: ('(1 2) 6)
Segmentation fault
But, if i try:
: ('(a b c) 6)
-> NIL
I mostly understand why, but it was a surprise that PicoLisp responded with a segfault instead of an error. Does this means that Picolisp doesn't check if a number is a function but it does... | (Lifted from picolisp mailing list.)
Yes, this is the expected behavior.
PicoLisp evaluates the CAR of a list, perhaps repeatedly, until it hits
upon a function. A function is either a list (then it is a Lisp-level
function) or a short number (then it is a built-in function, written in
either asm or C). If that number ... |
1,714,223 | 1,730,702 | Translating the Q and P function from The Little Schemer into Common Lisp? | In Chapter 9 of the Little Schemer, the Author presents the following two functions
(define Q
(lambda (str n)
(cond
((zero? (remainder (first$ str ) n))
(Q (second$ str ) n))
(t (build (first$ str )
(lambda ( )
(Q (second$ str ) n)))))))
(define P
(lambda (str)
... | I assumed:
In P definition, with "(Q (str (first$ str)))" you meant: "(Q str (first$ str))", as Q is a two-argument function.
build is a helper which does creates something on which first$ and second$ work: list
With this in mind, the direct translation of Scheme into Common Lisp gives:
(defun first$ (list) (first li... |
1,716,456 | 1,716,722 | Lisp as a Scripting Language in a C++ app | Hey, I've been looking at the possibility of adding a scripting language into my framework and I heard about Lisp and thought I would give it a go. Is there a VM for Lisp like Lua and Python or am I in the wrong mindset. I found CLISP here, http://clisp.cons.org/, but am not sure if this is what I am looking for.
Can a... | CLISP is just one implementation of Common Lisp. It's a very good implementation, and it does have some support for being embedded in other (C-based) programs, but that's not its focus and it's GPLed, which may or may not be a deal-breaker for you.
You might be interested in checking out ECL. This implementation is sp... |
1,717,838 | 1,940,954 | SOAP request from within an AutoLISP/AutoCAD macro | We have built a webservice for a client that uses AutoCAD. They have a macro that runs in AutoCAD that builds a SOAP request. But they have not figured out how to actually send() the soap request to us.
So the XML is all proper and ready to go, they just need to send it.
Anybody out there familiar enough with AutoLISP ... | To my knowledge AutoLISP does not have any native SOAP stuff. It does however have a fairly complete COM interface. You should be able to connect to any COM module that does whatever SOAP methods that you need.
|
1,719,551 | 1,719,706 | Getting the first n elements of a list in Common Lisp? | How would I get the first n elements of a list?
CL-USER> (equal (some-function 2 '(1 20 300))
'(1 20))
T
I am absolutely certain this is elementary, but help a brother newb out.
| Check out the SUBSEQ function.
* (equal (subseq '(1 20 300) 0 2)
'(1 20))
T
It may not be immediately obvious, but in Lisp, indexing starts from 0, and you're always taking half-open intervals, so this takes all the elements of the list with indices in the interval [0, 2).
|
1,720,147 | 1,720,362 | What does the SBCL time function return? | I'm trying to time an order statistic function implemented in SBCL. Googling around I found this timing function: (time form). However I'm not sure what it returns. It seems to be a large number but I can't find documentation specifying if the return value is milliseconds, nanoseconds, system time, etc.
Does anyone kn... | The TIME macro is specified to “pass trough” the value of whatever it runs. In this way, it is like PRINT (i.e. you can wrap TIME or PRINT around anything without changing the internal dataflow—they do add stuff to the output though). (time (foo)) returns whatever (foo) would return.
The specification provides no hard... |
1,721,716 | 1,721,996 | Calculating the depth of a binary tree in LISP recursively | I have the following binary tree
A
/ \
B C
/ \
D E
represented as a list in Lisp (A 2 B 0 C 2 D 0 E 0) where the letters are node names and the numbers are the number of child nodes (0 for none, 1 one node, 2 two nodes). I need to find highest from root node to leaf depth of the tree (the depth of the bin... | I would first transform the list to a tree:
(defun tlist->tree (tlist)
"Transforms a tree represented as a kind of plist into a tree.
A tree like:
A
/ \
B C
/ / \
F D E
would have a tlist representation of (A 2 B 1 F 0 C 2 D 0 E 0).
The... |
1,739,486 | 1,739,532 | Is there a common lisp package naming convention? | I have created some of my own user packages and have run into a name clash.
In Java, the naming convention is to use your domain name in the package name:
e.g. import com.example.somepackage;.
Are there any widely used package naming conventions for common lisp packages?
Regards,
Russell
| The convention I use is to use a unique word: salza, skippy, zs3, etc. I don't really try to have a direct relationship to the library functionality. I try to avoid generic words that others might use like "zlib" or "zip" or "png".
Edi Weitz uses Frank Zappa-related words to name many of his packages: Hunchentoot, Drak... |
1,751,911 | 1,753,850 | lambda-gtk negative pointer | I was trying to write my own put-pixel on (Gdk) pixbuf in Lisp. When I finally realized how I can operate on C pointers in CL, new obstacle came along - (gdk:pixbuf-get-pixels pb) returns me negative number. My question is: can I convert it somehow to a valid pointer? My attempts to use cffi:convert-from-foreign and cf... | I think that lambda-gtk incorrectly defined binding for pixbuf-get-pixels.
The negative value for pointer value might appear because of incorrect interpretation of unsigned integer as a signed integer.
The simplest way to correct this value is to use mod:
CL-USER> (mod -1 (expt 2 #+cffi-features:x86 32 #+cffi-features:... |
1,760,406 | 1,760,619 | Scheme - how do I modify an individual element in a list? | If I have a list of 0's, how would I modify, for example, the 16th 0 in the list?
| You have to write it yourself. It is not built in to Scheme because it's not idiomatic and it can be built easily from set-car!.
(define (list-set! l k obj)
(cond
((or (< k 0) (null? l)) #f)
((= k 0) (set-car! l obj))
(else (list-set! (cdr l) (- k 1) obj))))
If you are doing this a lot, you should probab... |
1,766,215 | 1,766,308 | Lisp code explanation | I'm porting some code from lisp, but I got stuck at this part (apparently that's for mit-scheme)
(define (end-of-sentence? word)
(and (or (char-exist-last? word '#\.)
(char-exist-last? word '#\!)
(char-exist-last? word '#\?))
(not (initial? word))
(or (eq? (peek-char) '#\Space) ;;p... | I'm no scheme programmer, but it appears that characters are being consumed in read-char source
end-of-sentence? on the other hand appears to be getting called without a parameter, even though it is declared to take one. I assume that the functions it calls in turn are tolerant to whatever the system provides for unsp... |
1,774,360 | 1,774,726 | To get my lisp code more robust | Dear all, I now have a preliminary macro
(defmacro key-if(test &key then else)
`(cond (,test
,then)
(t,else)))
and it is now correctly working as
> (key-if (> 3 1) :then 'ok)
OK
> (key-if (< 5 3) :else 'ok)
OK
> (key-if (> 3 1) :else 'oops)
NIL
> (key-if (> 3 1) :else 'oops :then 'ok)
OK
... | I assume that you are using some Common Lisp implementation.
That style of argument parsing is not directly supported by the standard lambda lists used by DEFMACRO. You are right in thinking that you will have to parse the arguments yourself (you could use (test &rest keys-and-forms) to capture TEST, but extracting the... |
1,776,798 | 1,776,902 | "Unable to resolve symbol" error | When I paste this code into a REPL, it works fine:
(use 'clojure.contrib.seq-utils)
(defn- random-letter [] (char (+ (rand-int 26) 97)))
(defn- random-digit [] (rand-int 10))
(defn- random-password
"Returns an 8-character password consisting of letters and digits as follows: aa1aa1aa"
[]
(let [password (interpose... | I don't know why you're having problems compiling this with :gen-class but I wouldn't be surprised if eval had something to do with it. eval is usually a bad idea. One thing to try (completely untested) is to use ` (backquote) instead of ' (quote) so that your symbols are namespace-qualified. Don't know if that'd he... |
1,778,464 | 1,778,479 | Common Lisp: Attach x recursively to list | I'm trying to add, say, x to every element of a list.
For example:
(queue 3 '(1 2 3))
would give
((3 1) (3 2) (3 3))
The code below apparently does not do what I want.
Any hints please?
(defun queue(x y)
(cond
((null y) nil)
(t (cons x (queue x (rest y))))))
| You're prepending x to to the result of applying queue to the rest of y, without using y's first element at all. So basically you're throwing away all values of y and replacing them with x.
You want to do (cons (list x (first y)) (queue x (rest y)))))) instead.
You could of course just use map to do this, but I assume ... |
1,786,647 | 1,786,672 | A simple Lisp question | I now have a problem on using "reduce" to implement my own version of copy-list.
This is what I have done:
(defun my-copy-list (lst)
(reduce #'(lambda (x y)
(cons x y))
lst :initial-value nil :from-end t))
However, my teacher said there is no need to use that lambda, I am confused on thi... | What your teacher means is that you're defining this function
(lambda (x y) (cons x y))
But there's already a function that exists to do that -- cons itself. So instead of passing your lambda as an argument to reduce, you could just pass cons.
|
1,793,266 | 1,794,753 | Lisp Flavored Erlang - Messaging primitives | I've read through all the documentation, and most of the source of LFE. All the presentations emphasize basic lisp in traditional lisp roles - General Problem Solving, Hello world and syntax emulating macros.
Does anyone know how LFE handles messaging primitives? To specify a more precise question, how would you expr... | I'm not an LFE user, but there is a user guide in the source tree. From reading it I would guess it is something like this:
(let ((A 2))
(let ((Pid (spawn (lambda ()
(receive
(B (when (is_integer B))
(: io format "Added: ~p~n" (list (+ A B))))
... |
1,800,896 | 1,800,915 | In Which Cases Is Better To Use Clojure? | I develop in Lisp and in Scheme, but I was reading about Clojure and then I want to know, in which cases is better to use it than using Lisp or Scheme? Thanks
| "Clojure runs on the JVM" means you get the whole cornucopia of Java libraries available. You can make pretty GUIs in Swing, use Apache's Web client or server code, connect a ready-built Sudoku solver... whatever you like.
Another big plus of Clojure is its very polished concurrency support, with about 3 different flav... |
1,822,382 | 1,822,579 | A lisp function refinement | I've done the Graham Common Lisp Chapter 5 Exercise 5, which requires a function that takes an object X and a vector V, and returns a list of all the objects that immediately precede X in V.
It works like:
> (preceders #\a "abracadabra")
(#\c #\d #r)
I have done the recursive version:
(defun preceders (obj vec &optio... | a typical parameter list for such a function would be:
(defun preceders (item vector
&key (start 0) (end (length vector))
(test #'eql))
...
)
As you can see it has START and END parameters.
TEST is the default comparision function. Use (funcall test item (aref vector i)).
... |
1,836,725 | 1,846,811 | Deductive Retriever Example | In Lisp, suppose I have these two rules in the knowledge base:
(append nil ?x ?x)
(<- (append (cons ?x ?l1) ?l2 (cons ?x ?l3))
(append ?l1 ?l2 ?l3))
Then how could I infer that if we ask
(ask '(append (cons a (cons b nil))
(cons c nil)
?l)
'?l))
we will get the result '((cons a (c... | To understand the problem, I think you'll need to acquire two key concepts first: backward chaining and unification.
With gross simplification, here is how backward chaining works: try if it is possible to unify the goal (the first argument for 'ask' in your example) with the head of any of the rules (note the nondet... |
1,837,050 | 1,837,250 | Building IP and Port from Byte Buffer | I have a byte buffer 6 bytes long first four contains ip address last 2 contains port, in big endian notation.
to get the ip i am using,
(apply str (interleave (map int (take 4 peer)) (repeat ".")))
Is casting bytes to int safe to get the ip address?
and also in java i use,
int port = 0;
port |= peerList[i+4] ... | yes mapping them to should be safe in this case because any leading zeros that are intoduced by writing into a larger data type will drop away again when it is converted into a string
The second part gets a lot easier because you are starting with a list of bytes.
(+ (* 256 (nth 5 peer)) (nth 4 peer))
A more genera... |
1,838,679 | 1,838,795 | returning a lambda function in clisp, then evaluating it | Suppose I have this wonderful function foo
[92]> (defun foo () (lambda() 42))
FOO
[93]> (foo)
#<FUNCTION :LAMBDA NIL 42>
[94]>
Now, suppose I want to actually use foo and return 42.
How do I do that? I've been scrounging around google and I can't seem to come up with the correct syntax.
| You want the FUNCALL function:
* (defun foo () (lambda () 42))
FOO
* (funcall (foo))
42
|
1,841,053 | 1,841,102 | a simple lisp function | I wrote a test function to test my understanding of "return-from" in Lisp
(defun testp (lst)
(mapc #'(lambda (x y)
(if (null lst)
(return-from testp t)))
lst
(cdr lst)))
I think the test (testp 'nil) should return T but it returns NIL.
Could you please help my understandin... | You call MAPC over two empty lists.
How should the LAMBDA function ever be used if the lists don't have any elements to map over?
Btw., you can write 'list' instead of 'lst'.
(defun testp (list)
(mapc #'(lambda (x y)
(if (null list)
(return-from testp t)))
list
(cdr list)))... |
1,852,891 | 1,852,958 | Association in Common Lisp | There's a structure of the following format:
(setq dist '(((1 1) 1)
((0 2) 3)
((1 2) 1)
((2 3) 3)
((3 5) 4)))
Is there any function which, if I call
(myf '(0 2))
could give me
3
or
((0 2) 3)
Something like a reverse assoc
| I fail to see why this would be called a reverse ASSOC.
(assoc '(0 2) dist :test #'equal)
> ((0 2) 3)
It looks like ASSOC works fine, provided you change the test function, so that lists used as keys are correctly tested.
|
1,857,083 | 1,857,130 | How Functional language are different from the language implementation point of view | There is the whole new paradigm of "functional programming", which needs a total change of thought patterns compared to procedural programming. It uses higher order functions, purity, monads, etc., which we don't usually see in imperative and object oriented languages.
My question is how the implementation of these la... | Implementations of Functional Programming languages are using a wide range of implementation techniques. An excellent introduction into the implementation of Scheme (a Lisp dialect) gives this book: Lisp in Small Pieces by Christian Queinnec.
|
1,859,505 | 1,860,113 | Lisp difference between (cons 'a (cons 'b 'c)) and (cons 'a '(b.c)) | What's the difference between:
(cons 'a (cons 'b 'c)) ;; (A B . C)
and
(cons 'a '(b.c)) ;; (A B.C)
I need to create the following list ((a.b).c) using cons so i'm trying to understand what that "." represents.
L.E.: I have the following (cons (cons 'a 'b) 'c) but it produces ((A . B) . C) and not ((A.B).C) (Note the... | Spaces are used to separate list tokens. A.B is a single token. (A.B) is a list with a single element. (A . B) is a cons cell with A as car and B as cdr.
A cons cell is a pair of "things" (objects). In your case, these things are symbols, and they are named A, B, etc.. The printed representation of such a cell is ... |
1,860,696 | 1,860,778 | Returning an element from a list | I'm trying to learn lisp and as i'm making my first steps i got stuck.
How can i get c element form following list: (a b (c.d))
I've tried: (caar (last '(a b (c.d)))) but it returns c.d and not only c
This however works if there are spaces between c, . , d ie: (caar (last '(a b (c . d))))
The problem i'm trying to re... | Your code is right, it's a typo (or maybe a really bad font?) in the exercise.
In Lisp (Common Lisp and Scheme are the two I tested just now, I don't know about Clojure), [nearly] the only divisions between symbols are spaces and parentheses. Even though . is used as literal syntax for cons, if you type '(c.d), you ge... |
1,864,795 | 1,864,858 | What does "my other car is a cdr" mean? | Can anyone well versed in lisp explain this joke to me?
I've done some reading on functional programming languages and know that CAR/CDR mean Contents of Address/Decrement Register but I still don't really understand the humour.
| In Lisp, a linked list element is called a CONS. It is a data structure with two elements, called the CAR and the CDR for historical reasons. (Some Common Lisp programmers prefer to refer to them using the FIRST and REST functions, while others like CAR and CDR because they fit well with the precomposed versions such a... |
1,865,820 | 1,866,823 | SBCL standard library documentation? | I want to learn and use SBCL because of its ease of learning and speed. (I've been playing with Lisp 3 years ago, and now am refreshing it.) But how can I learn what's included in the standard library, so that I don't re-implement things?
After Python this is like a nightmare: the SBCL website has a manual that covers ... | Firstly: that problem isn't really SBCL specific. The CL library is standardised and thus you can use the documentation of any lisp.
As mentioned, the CL HyperSpec is very useful. It is however a reference and thus not very suitable for learning in my opinion.
For learning, there are various books out there. I perso... |
1,867,623 | 1,869,182 | Homework: Lisp items that appear more than once in a list | Given a list, I'm trying to return a new one that has only the items that appear more than once in the first list I receive as a parameter.
I have done the following:
(defun myf (lista)
(if (endp lista)
nil
(if (member (first lista) (rest lista))
(append (list (first lista)) (myf (rest lista)))
... | Vincent, Gishu and Jerry hinted that you need to check if the item is already in the result list before appending to it, while Derek hinted that you could modify the original list when you see that an item is repeated.
Read the documentation of the functions adjoin and remove here:
http://www.lispworks.com/documentatio... |
1,868,569 | 1,869,414 | Compiling to idiomatic C | Are there any compilers out there for function or lisp-ish languages that compile to idiomatic C? Most compilers out there seem to provide something resembling a machine language composed of C macros. I'm wondering if there is anything out there that can produce readable C code based on a higher-level language.
| For Common Lisp there is currently only one widely used compiler that compiles to C: ECL. You would need to look if the output it is readable enough.
Years ago a company sold a Common Lisp compiler for exactly this purpose: compiling Lisp to 'maintainable' C. The compiler was very expensive. It is no longer available, ... |
1,868,807 | 1,868,835 | Elisp function returning mark instead of the right value | I'm writing a routine to test to see if point is at the practical end of line.
(defun end-of-line-p ()
"T if there is only \w* between point and end of line"
(interactive)
(save-excursion
(set-mark-command nil) ;mark where we are
(move-end-of-line nil) ;move to the end of the line
(let ((s... | There is a built-in function called eolp. (edit: but this wasn't what you were trying to achieve, was it..)
Here is my version of the function (although you will have to test it more thoroughly than I did):
(defun end-of-line-p ()
"true if there is only [ \t] between point and end of line"
(interactive)
(let (
... |
1,869,763 | 1,869,842 | How can Lisp make me a better C# developer? | I'm considering learning a Lisp dialect (probably Scheme, since I am constantly hearing how good of a learning language it is) in order to improve my general programming skill.
Apart from the fact that learning any new language helps you to be a better programmer in general, how can learning Lisp make me a better C# pr... | I think the best you can gain from studying a functional language is starting to think in a more declarative, less imperative way. That will lead to writing more readable, maintainable and composable code.
Another thing you learn when you go functional is the importance of pure functions, i.e functions without side-eff... |
1,877,318 | 1,879,628 | Another Lisp function refinement | I've completed the Graham's exercise Chapter 5.8,and my code is:
(defun max-min (vec &key (start 0) (end (length vec)))
(cond
((eql start (1- end)) (values (elt vec start) (elt vec (1- end))))
((zerop end) (values nil nil))
(t
(multiple-value-bind (x y) (max-min vec :start (1+ start) :end end)
... | Your lambda list is OK. The problem is the base case: (zerop end) should be modified so that you also get a sensible result if called like (min-max myvec :start 5 :end 3).
The next critique is about these two lines:
(multiple-value-bind (x y) (max-min vec :start (1+ start) :end end)
(let* ((maxx x) (minn y))
... |
1,885,019 | 1,885,093 | How do I write all-but-one function in Scheme/LISP? | Can you guys think of the shortest and the most idiomatic solution to all-but-one function?
;; all-but-one
;; checks if all but one element in a list holds a certain property
;; (all-but-one even? (list 1 2 4)) -> true
;; (all-but-one even? '(1)) -> true
;; (all-but-one even? '(2 4)) -> false
Edit: all but EXACTLY one... | With a better name:
(define (all-except-one pred l) (= 1 (count (negate pred) l)))
(But this is PLT specific.)
|
1,894,209 | 1,894,891 | How to read mentally Lisp/Clojure code | Thanks a lot for all the beautiful answers! Cannot mark just one as correct
Note: Already a wiki
I am new to functional programming and while I can read simple functions in Functional programming, for e.g. computing the factorial of a number, I am finding it hard to read big functions.
Part of the reason is I think be... | Lisp code, in particular, is even harder to read than other functional languages because of the regular syntax. Wojciech gives a good answer for improving your semantic understanding. Here is some help on syntax.
First, when reading code, don't worry about parentheses. Worry about indentation. The general rule is that ... |
1,910,003 | 1,910,132 | lisp-style style `let` syntax in Python list-comprehensions | Consider the following code:
>>> colprint([
(name, versions[name][0].summary or '')
for name in sorted(versions.keys())
])
What this code does is to print the elements of the dictionary versions in ascending order of its keys, but since the value is another sorted list, only the summary of its firs... | Why not exploit tuples?
colprint([(name, version[0].summary or '')
for (name, version) in sorted(versions.iteritems())])
or, even
colprint(sorted([(name, version[0].summary or '')
for (name, version) in versions.iteritems()]))
Also, you may consider (in my first example) removing the []s, because t... |
1,919,097 | 1,922,724 | Functional Programming: what is an "improper list"? | Could somebody explain what an "improper list" is?
Note: Thanks to all ! All you guys rock!
| I think @Vijay's answer is the best one so far and I just intend to Erlangify it.
Pairs (cons cells) in Erlang are written as [Head|Tail] and nil is written as []. There is no restriction as to what the head and tail are but if you use the tail to chain more cons cells you get a list. If the final tail is [] then you g... |
1,926,835 | 1,926,848 | How to write an interpreter? | I have decided to write a small interpreter as my next project, in Ruby. What knowledge/skills will I need to have to be successful?
I haven't decided on the language to interpret yet, but I am looking for something that is not a toy language, but would be relatively easy to write an interpreter for.
Thanks in advance.... | You will have to learn at least:
lexical analysis (grouping characters into tokens)
parsing (grouping tokens together into structure)
abstract syntax trees (representing program structure in a data structure)
data representation (assuming your language will have variables)
an evaluation loop that "runs" your program
... |
1,930,901 | 1,931,062 | Exclusive OR in Scheme | What is the exclusive or functions in scheme? I've tried xor and ^, but both give me an unbound local variable error.
Googling found nothing.
| I suggest you use (not (equal? foo bar)) if not equals works. Please note that there may be faster comparators for your situiation such as eq?
|
1,934,551 | 1,934,559 | What is the difference between require and load in common lisp? | I'm going through Practical Common Lisp, I'm almost finished, and one question that has not been answered for me so far (or maybe I just missed it) is the difference between "require" and "load".
So what is the difference?
Thanks.
| require is used for modules, which can each consist of one or many files.
load is used to load an arbitrary single file.
The require function tests whether a
module is already present (using a
case-sensitive comparison); if the
module is not present, require
proceeds to load the appropriate file
or set of fi... |
1,963,125 | 1,963,152 | Trying out the examples from the "The Little Schemer" book in Windows | I am currently reading 'The Little Schemer' and I need a way to test out the Scheme examples in the book on my Windows machine.
With what application can I do this (on Windows, not Linux)?
| PLT Scheme is a very good self-contained Scheme development environment available for several platforms including Windows. It comes with several flavors of Scheme, an IDE with a debugger, and a ton of Scheme libraries for real-world programming.
|
1,965,301 | 1,965,342 | Syntax changes from the examples in 'The Little Schemer' to the real Scheme | I have recently started following the examples from The Little Schemer and when trying out the examples in DrScheme, I have realised that there are some minor syntax changes from the examples in the book to what I can write in DrScheme.
First of all, as a language in DrScheme, I chose Pretty Big (one of the Legacy Lang... | IIRC, the book uses a different font for quoted pieces of data, and in real Scheme code that requires using quote. As for your use of PLT Scheme -- the "Pretty Big" language is really there just as a legacy language. You should use the Module language, and have all files start with #lang scheme (which should be there... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.