scheme,lisp,common-lisp , Simulate scheme define in common lisp

Simulate scheme define in common lisp


Tag: scheme,lisp,common-lisp

I wonder how to simulate the scheme define in common lisp,and want to write a macro for simulate the define. So what's the different between cl's defun deparameter defvar and scheme's define ,and how i can do this?


define in Scheme is not easily implemented in Common Lisp. It's not easily implemented in Scheme either. It's transformation is different in different scopes:

(define test value)              ; defines test, value can be anything even (lambda ..) which makes a procedur object
(define (test arg ...) body ...) ; defines the procedure test

(define (somefun)
  (define test ...)
  (define (test2 x) ...)

Is a fancey way of writing:

(define (somefun)
  (letrec ((test ...)
           (test2 (lambda (x) ...))

So what are the eqvivalents in Common Lisp:

(define myplus otherfun)             ; (setf (symbol-function 'myplus) otherfun)
(define myplus (lambda args . body)) ; (defun myplus args . body)
(define (myplus . args) . body )     ; (defun myplus args . body)
(define value 10)                    ; (defparameter value 10)

Here is my take on the macro. Still this won't work for internal defines:

(defmacro define (name-or-ll &body expressions)
  (flet ((dotted-to-rest (lst)
           (let ((last (last lst)))
             (if (null (cdr last))
                 (append (butlast lst)
                         (list (car last) '&rest (cdr last)))))))

    (cond ((consp name-or-ll)             ; (define (fun a b) ...)
              (defun ,(car name-or-ll) ,(dotted-to-rest (cdr name-or-ll)) ,@expressions)
              (defparameter ,(car name-or-ll) #',(car name-or-ll))))
          ((and (consp (car expressions)) ; (define fun (lambda (a b) ...)) 
                (eq (caar expressions) 'lambda))
            `(define (,name-or-ll ,@(cadar expressions)) ,@(cddar expressions)))
          (t `(let ((value ,(cons 'progn expressions)))                
                (when (functionp value)
                  (setf (symbol-function ',name-or-ll) value))
                (defparameter ,name-or-ll value))))))

(define proc (lambda (x) (* x x)))
(define myproc proc)
(define myplus #'+)
(define test 'test)
(define (testproc a b) (+ a b))
(define testproc2 (lambda (a . b) (apply myplus a b)))
(list (proc 10) (myproc 10) 
      (myplus 2 3) (testproc 2 3) 
      (testproc2 2 2 1) (funcall testproc2 2 2 1) 
      test) ; => (100 100 5 5 5 5 TEST)


If strings are vectors, why are they immutable?

if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

How would I make this Racket code DRYer?

I'm porting a Python script to Racket as a learning experience, and I have this function: (define (check-status) (define git [find-executable-path "git"]) (define-values (ckot out in err) (subprocess #f #f #f git "checkout" "-q" "master")) (define-values (local lout lin lerr) (subprocess #f #f #f git "rev-parse" "@")) (define-values (remote rout...

Generating n-grams with foldl in Racket

So I'm fiddling with Racket. Recursively generating n-grams from a list of words was pretty straightforward: (define (n-grams-recursive words n) (if (< (length words) n) '() (cons (take words n) (n-grams-recursive (cdr words) n)))) And the iterative version also pretty straightforward: (define (n-grams words n) (define (iter n-grams remaining-words) (if...

Insertion into a list doesn't reflect outside function whereas deletion does?

I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

How to move a file in Lisp using rename-file

What's the best way to move a file in Lisp in an implementation-independent way? For example I have an image file: (setq oldpath #P"SERVER:PICTURES;TEMP;PHOTO.PNG") and I want to move it out of the TEMP directory into the PICTURES directory. This seems to work: (setq newpath (make-pathname :host (pathname-host oldpath) :directory...

Understanding “let” expression in LISP

I am extremely new to lisp, had previous experience with functional programming (Haskell, SML). Why is this code returning 14, and not 10 (ie. 1 + 2y + 3 + 1)? (defvar x 1) (defun g (z) (+ x z)) (defun f (y) (+ (g 1) (let ((x (+ y...

Backquote String Interpolation

Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

Racket\Scheme compare and delete unwanted items in a list

I have 2 lists: (Define list1 '("xx1" "xx2" xx3" "xx4" "xx5")) (Define list2 '("xx2" "xx4" "xx5")) the items in the list above are just an example, but either way it will be a string item. What I need to do is compare both lists and remove the items in list1...

LISP: read number from user and commpare with array index

Hello guys I'm new In functional programming Really it is not Clear for me anyone can help me ? My Question just for getting the philosophy of writing on Functional programming language for example how I can write a program in Lisp language for reading the user inputs and compare...

“Mapping” Little Schemer to coderbyte challenge: Capitalize

After studying most of The Little Schemer, I've been trying my hand at some recursive solutions to Coderbyte challenges. After some fiddling I threw in cons and thought my upperConsIt would work to look through an array, find all of the instances of a particular letter and capitalize each. Ultimately,...

how to change the value of sp-navigate-reindent-after-up in smartparens

I want to change the default behavior of smartparens to remove the whitespace before the close delimiter. I mean, when I type ) after (a b c |, I hope the final result is (a b c)|. Here, the | is cursor. I searched the documentation of smartparens, and find...

Scheme several actions if an if-statement proves true

The way I understand a scheme if-statement is that the first condition is when the if-statement is true, and the second statement is when it is false. What if I want several conditions for when the statement proves true? An example: (if (= a b) (set! ([a 2])) // This...

Append string to existing textfile in IronScheme

We are trying to construct a log file using IronScheme, and we have written a code for it using racket. It works fine in racket, but IronScheme throws an error. This is what we have so far: (define write-to-log (lambda(whatToWrite) (with-output-to-file "robot-log.txt" (lambda () (printf (string-append whatToWrite "\r\n" ))) #:exists...

Is there a way to see the body of a lambda in Racket?

Say I have this code: #lang racket (define a ((λ (x) x) ((λ (y) y) (λ (z) ((λ (w) w) z))))) I know intuitively that this lambda expression is (extensionally) equal to (λ (z) z) My question is if there is a way to print out the body of a...

Writing a While Loop in Scheme

I am trying to implement a while loop using recursion with lambda, but I just don't understand how to do it. I am supposed to start with this lambda expression: ((lambda (x) (x x)) (lambda (x) (x x)) My first question is why does this cause 'eternal' recursion? I try...

require/typed contract in racket fails

I've tried looking at the docs but i can't find an example that i can use for my case. I need to import break from srfi/1. Here's my attempt. The example works in #lang racket. #lang typed/racket (require/typed (only-in srfi/1 break) ;[break (All (T) (-> (-> T Boolean) (Listof T)...

Common Lisp Object System method execution order

I have the following two classes: (defclass person () ()) (defmethod speak ((s person) string) (format t "-A" string)) (defmethod speak :before ((s person) string) (print "Hello! ")) (defmethod speak :after ((s person) string) (print "Have a nice day!")) (defclass speaker (person) ()) (defmethod speak ((i speaker) string) (print "Bonjour!"))...

Implement yield and send in Scheme

I'm trying to port yield and yield from from Python to Scheme. Here is an implementation I've done: (define (coroutine routine) (let ((current routine) (status 'new)) (lambda* (#:optional value) (let ((continuation-and-value (call/cc (lambda (return) (let ((returner (lambda (value) (call/cc (lambda (next) (return (cons next value))))))) (if (equal? status 'new) (begin...

How to get only specific elements of list in racket

Input: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73) ("june 101" 55 55) ("june 104" 55 54) ("aug 201" 220 220)) Desired output: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73)) How do I achieve this? I only want the may terms....

Defining cons, car and cdr with lambda - how does it work? [duplicate]

This question already has an answer here: Use of lambda for cons/car/cdr definition in SICP 2 answers I can't seem to explain how this definition of cons, car and cdr works: (define (p-cons x y) (lambda (proc) (proc x y))) (define (p-car proc) (proc (lambda (p q) p))) (define...

Are Lisp lists always implemented as linked lists under the hood?

Are Lisp lists always implemented as linked lists under the hood? Is this a problem as far as processor caching goes? If so, are there solutions that use more contiguous structures which help caching?...

Using MIT/GNU Scheme

I have downloaded the MIT/GNU Scheme implementation of LISP in order to understand Structure and Interpretation of Computer Programs. However, I am a bit confused about what I am dealing with when I launch the program. When the program is launched, I get two windows: the "MIT/GNU Scheme" window, and...

Scheme define-macro and/or define-syntax

I want to create an overloaded Scheme macro for a simple form of polymorphism. That is, a macro smart enough to expand differently when given params of different types, so that (look-up key container) does the "right" thing for different kinds of containers. (define-macro (look-up key container) (cond ((table? container)...

Translate Scheme closure-defining function into Haskell

The following procedure, written in Scheme, (define (eat xs) (lambda (x) (if (eq? x 'vomit) (reverse xs) (eat (cons x xs))))) can be called in the following way: > eat #{procedure 9165 eat} > (eat '()) #{procedure 9166 (unnamed in eat)} > ((eat '()) 1) #{procedure 9166 (unnamed in eat)}...

No-argument (and) returns t

Both CL and Scheme define (and) to return t (or #t) with no arguments. I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true. Edit: clojure follows the...

Get element from list of list in lisp

I am a beginner with lisp. I manipulate list of list: ((name1, second) (name2, second2)) The goal of my function is to get the second element of the list that have name as it first node. For example: my list is: ((name1, second1) (name2, second2)) getelement list name1 should return...

Modify list and return it inside a function in lisp

(defun testthis (node index newvalue) (set-nth node index newvalue) node ) I would like to modify the nth element of a list in a function and then returns this list to save the modification performed. How can I do a such function in lisp?...

How is it possible to filter a list of directories via “directory-exists?”?

I recently discovered a strange behaviour of racket: Whenever I try to filter a list of directories created via directory-list my REPL returns me an empty list, but when I try the same with an quasiquoted list my REPL returns a correctly filtered list. My questions is now: Why it's...

Structuring large Lisp applications

I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

Return items of a list in Lisp

I have to write a program in Lisp that returns the first item of a list if it contains an even number of elements, and the last if it contains an odd number of elements. I need a little advice on where to start? I don't need whole program.

Accessing call stack depth in Scheme

In order to demonstrate the effectiveness of tail recursion, I would like a way to access the depth of the call stack dynamically in Scheme. Is there a way to do this? If not, is there a way to do this in other major functional languages (OCaml, Haskell, etc.)?...

Scheme - unpack list's elements into function [duplicate]

This question already has an answer here: How do I pass a list as a list of arguments in racket? 2 answers I have a function which takes an unlimited number of args such as (define (func . args)). Say I have a list '(1 2 3), how do...

Exceed evaluation depth when forward function in Emacs Lisp

Here is just a simplified code snipped I have not managed to work. I do not understand what is wrong. (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index))))) The following...

How to create a list of sublists in Lisp without map?

I'm trying to make a function that creates a list of all sublists in the given list. What I mean is, when I've got a list: (4 (a g b) g (1 2 3) g (4 5 6)) I want a list: ((a g b) (1 2 3) (4 5...

Scheme nested lambda function

I am a beginner in Scheme. I found this question in MIT exam 1 for SICP lecture. What's the value and type for – ((lambda (a) (lambda (b) (+ (sqrt a) (sqrt b)))) 5) I am having a hard time understanding how this function works. I am really confused about...

How to use FFI:def-call-in in clisp

I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in. I don't know the process and actually I am confused if clisp will also create some .so file that...

How would I get the min/max of a list using a key

I currently have a list of objects, each containing a certain attribute. I would like to get the element of the list with the min attribute value. Is there a concise way of doing this? The python equivalent would be something like: min(d, key=d.get) Is there a way of getting...

EVAL/APPLY: too many arguments given to F

Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Invalid specialized parameter in method lambda list

I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

How to use a parameter in a macro call?

I have defined the following simple macro: (defmacro define-class (class-name) `(defclass ,class-name ()())) And now I want to use it in the following function: (defun create-data (mode) (define-class mode)) After compiling the last function I get the following message, the variable MODE is defined but never used. And when I...

Common Lisp - Giving &rest Lists as Arguments

As a result of musings around an exercism problem, I am trying to write a function that takes an input number and an arbitrary length list of divisors to test, along with the expected divisibility (i.e. remainder 0) as a boolean, returning true if all expectations are met (defaulting to...

lisp remove a the content of one list from another list

I have a list of string like this called F: ("hello word i'am walid" "goodbye madame") => this list contain two elements of string and I have another list call S like this ("word" "madame") => this contain two words now I want to remove the elements of the list...

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

Value from binding in LFE interpreter using Erlang

I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

Create lists from lists

I want to write a function which for n arguments will create n lists and each contains n-th element for every argument, for example: (aux '(1 2) '(3 4)) = `((1 3) (2 4)) I wrote such a function: (define (aux . args) (if (null? args) '() (cons (map car...

Printing ith row jth column value in lisp

I am taking input N as number of rows of a 2D matrix in lisp, where each row can have maximum of 5 elements in it. So i make it like this. Now for eachrow as it can have any number of elements between 0 to 5. So I made...

Char Comparison in Common Lisp

How can i compare characters with Common Lisp? I have google it and found out that there are some functions to do the comparison, like char=, char/=, char<, char>, char<=, and char>=. But, i can't use all of the functions just like: (char= 'a 'a) (char< 'a 'b) If i...

Returning an element and then deleting the element from a list in Scheme

I have a list in Scheme which contains numbers. I wrote a function that takes as input one number and a list of objects and checks if the confidence value of the object matches the number. Once I get the object whose confidence values matches the given number, I want...

Any history background about the “yin-yang puzzle” in detail?

There are quite a few questions about the "yin-yang puzzle" already in Stackoverflow: How does the yin yang puzzle work? (I assume this is the first one) Haskell (this is my question) C# 5.0 Typed languages ... (there could be something I didn't find yet) I was wondering when and...