arguments,lisp,common-lisp,sbcl , Common Lisp - Giving &rest Lists as Arguments

Common Lisp - Giving &rest Lists as Arguments


Tag: arguments,lisp,common-lisp,sbcl

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 true if unspecified).

example input:

 (divisible-by 10 (5 t) (4 f) 2) => t

My reading has lead to this attempt at creating the input for the function:

(defun divisible-by (numerator &rest args (&key divisors (divisorp t)))

My simple test cases for such an input type error out in various ways, and my searching via Google and directly here on Stack Overflow have not proved fruitful, leading me to believe my understanding is insufficient to generate the right keywords.

Pointers on how to implement such a function, where my attempts fall down or why such a function cannot be implemented as I have outlined would be gratefully received.


You don't need anything beyond &rest:

(defun divisible-p (number &rest divisors)
  "Check whether number is divisible by divisors."
  (dolist (spec divisors t) ; For each 'divisor' in divisors
    (etypecase spec
      ;; If divisor is a list, test if modulus of first value is 0
      ;; then compare to second (boolean)
      (cons (unless (eq (zerop (mod number (first spec)))
                        (second spec))
              (return nil)))
      ;; If divisor is an integer, return t if modulus == 0
      (integer (unless (zerop (mod number spec))
                 (return nil))))))

(divisible-p 10 '(5 t) '(4 nil) 2)
==> T
(divisible-p 10 '(5 t) '(4 nil) 2 3)
==> NIL

Note that you need to quote list arguments, otherwise you will get an error that there is no function 5.

I am not sure what you were trying to accomplish by using &key, but they cannot be repeated in CL, i.e., if you write

(defun foo (&key a) (print a))
(foo :a 1 :a 2 :a 3)

only 3 will be printed, 1 & 2 will be ignored.


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...

agrep working with del, ins arguments

How can "abteam" with "ab" be matched using this code? agrep("abteam",c("acb","abd","ab"),value=T, = TRUE,max = list(del = 10, ins = 10, sub = 10)) The result is character(0), though I specified del=10, ins=10. What is the problem? How does agrep work?...

Flash AS3 Crashing After A Multiple Clicks - Argument Error - noSource error

I have here, some AS3 that is used to create a 19 button interactive kiosk. It calls 20 different video_files to be played in an FLVPLayer. When one button is clicked, it draws the player and specifies the source. Whats happening is on our PC, is our crazy-kid-test, where we...

R: pass a vector of symbols into a function instead of a long argument list

I'm writing an R package that calls C code with the .C() function. I need to pass over 50 arguments into .C(), which seriously bloats my code and is prone to error. Rather than type output <- .C("my_dynlib", arg2, arg3, arg4, arg5, arg6, ..., arg53) I would rather have a...

JavaScript - If a function is passed as an argument, can it be returned as a string before the function is evaluated?

Consider the following code: function add(a,b) { return a + b; } function displayFunction(func) { console.log(_WHAT_SHOULD_GO_HERE_); // I want to log 'func' to the console } displayFunction(add(2,3)); // I want this to log "add(2,3)" Is this even possible to do in JavaScript?...

passing arrays to a function in erlang

I am new to erlang programming and as a matter of fact no very experienced programmer. I need to pass an array to a function and then manipulate it.. however I have so far not be this what I found. module(easy). export([myfunction/1]). myfunction([myarray]) -> %% mycode.. hier I will need...

variables in system() call C++

I have a variable in argv[1] which I need to call inside another c++ file in such a way: system("./assemblerL.out", argv[1]); this above is incorrect syntax as I am getting "too many arguments" errors. What is the correct way of doing this?...

Derive a class name from another class name in template

In order to use a library, I need to use different classes that have the same base name. I.e. MyClass MyClassImpl PreMyClass And so on. in order to use them with template I need pass all these class names. template <typename T, typename TImpl, typename PreT> class ClassThatUsesAllTheseObjects { public:...

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!"))...

get index of subtable from function args in lua

Im trying to return the value of an index of a table which is inside of another table and am doing so using the args given when a function is run so that the arg resolves to a variable name. function getsubindex(varname,index) local tbl = {} tbl.first = 99 tbl.subTbl...

Reading a table when function has many argument return an error

I'm trying to read an array inside a Lua function in a library that I'm developing. When I call the function with one argument, like xyz = {3, 4, 5} setxyz(xyz) I read the array correctly, while if I add a second argument xyz = {3, 4, 5} setxyz(xyz, 3)...

how to initialize a parameter in javascript function when i define the function

i have a defined a function with a parameter in javascript, and i don't know how to initialize it's parameter, any one help me. the code is bellow <br/>Enter a number: <input type="text" id="txt1" name="text1"> <p>Click the button to see the result</p> <button onclick="myFunction(5)">show result</button> <br/> <p id="demo"></p> <script> function...

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...

Add hash argument or string argument in a method to a hash (Ruby)

If the argument "entry" to the method add is a hash I need to add it to the :entries hash. If "entry" is a string "entry" needs to be set as a key in the hash and its value to nil. I have a solution below but is there a...

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...

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...

What is fn.bind.apply(fn, arguments) doing?

I saw this shortcut given as an answer on a code Kata but I am having difficulty understanding exactly what the below example is doing. function func(fn) { return fn.bind.apply(fn, arguments); } So far my understanding is that bind creates a new function similar to doing the following: function func(fn)...

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...

Extract Argument from C Macro

I have a number of definitions consisting of two comma-separated expressions, like this: #define PIN_ALARM GPIOC,14 I want to pass the second expression of those definitions (14 in the case above) to unary macros like the following: #define _PIN_MODE_OUTPUT(n) (1U << ((n) * 2U)) How can I extract the second...

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?

Dynamic arguments for Python functions [duplicate]

This question already has an answer here: Expanding tuples into arguments 3 answers I have a list of lists, and I would like to enter them into a function in such a way that each element of the main list is a different argument to the function. squares =...

Python command line arguments linux

I have this little program(I know there is a lot of errors): #!/usr/bin/python import os.path import sys filearg = sys.argv[0] if (filearg == ""): filearg = input("") else: if (os.path.isfile(filearg)): print "File exist" else: print"No file" print filearg print "wasn't found" If i start it by typing python testfile.txt...

Why do some methods accept only blocks as arguments in Ruby? [closed]

Methods like maps and collect only accept blocks. If blocks are not objects and can't be saved to variables, then why do these methods need them as arguments? multiples_of_2 = do |x| x % 2 == 0 end sq = { |x| x ** 2 } (1..50) #...

How do I identify the last variable argument? [duplicate]

This question already has an answer here: Count number of parameters in C variable argument method call 3 answers So in my function I want to take a variable number of char pointers. void myFunction(char *_Name, ...); Only, when I iterate through the arguments my code breaks because I'm...

How many parameter in this printf() function? [duplicate]

This question already has an answer here: How does printf handle its arguments? 5 answers I am very new to programming. Now I am learning C. Please look at this following code snippet - printf("StudentId: %d CGPA: %f", id, cgpa); printf("Name: %s StudentId: %d CGPA: %f", name, id, cgpa);...

Javascript arguments shifting

Let's assume that we have the following function: var a = function(data, type){ var shift = [].shift;;;;; console.log(data); } a(1,'test', 2, 3); I understand that data and type are just references to specific values in arguments. But why in the end, data is equal to 3?...

BASH: testing the number of arguments passed in an IF statement

i'm trying to send two arguments to .run file. $2 default should be 0. if $2 arg = 1 then grep -i a -1 --color -E $1 *.* else grep -i --color -E $1 *.* , something like this if [${2:-0} = 1] then grep -i a -1 --color -E...

Why does respond_to? need symbols as arguments in Ruby?

Why does this method only accept symbols and not strings as its arguments? x = 10 x.respond_to?(next) Pushing a string like the above would throw (ruby):1: void value expression....

Powershell Invoke-Command with PSCredential Cannot process argument transformation on parameter 'Credential'

I'm trying to run a powershell invoke-command call with a PSCredential as parameter. But the call fails with the error: Invoke-Command : Cannot process argument transformation on parameter 'Credential'. userName" Here is the detailed output I get : error 17-Jun-2015 14:33:53 Invoke-Command : Cannot process argument transformation on parameter 'Credential'....

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...

When are variables evaluated when passing them into functions?

This is probably a simple question, but I would really like to know the answer. Are the arguments passed into a function calculated once and set as local variables or are they calculated every time they're used inside the function? For example: When you write a forLoop, you should set...

Passing arguments to main in C using Eclipse

I have a program in Eclipse and I need to pass some arguments into main. More specifically, I need to pass 2 strings (which are numbers) and are needed to call some other functions. Here is my main: int main(int argc, char **argv) { int n = atoi(argv[0]); size_t size...

pass several arguments from a array to a function in a easy way -python-

Well i really don't know how to describe this in words but i've an easy example: def foo(x,y,z): r=x+.... a = [1,2,3] foo(a[0], a[1], a[2]) Can i do the same without calling a[n] several times? but keeping "x,y,z" definition...

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...

How to use `--foo 1 --foo 2` style arguments with Python argparse?

nargs='+' doesn't work the way I expected: >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument("--name", dest='names', nargs='+') _StoreAction(option_strings=['--name'], dest='names', nargs='+', const=None, default=None, type=None, choices=None, help=None, metavar=None) >>> parser.parse_args('--name foo --name bar'.split()) Namespace(names=['bar']) I can "fix" this by using --name foo bar, but that's unlike other tools I've used, and...

ORA-00939: too many arguments for function in CASE Statement

I'm getting the ORA-00939: too many arguments for function error from my case statement. I have tried splitting it up into multiple CASE statements but still get the same error. CASE WHEN l.fridge_door_modela_id = 'II-SH' THEN 'IW' WHEN l.fridge_door_modela_id = 'IIC-SH' THEN 'IW' WHEN l.fridge_door_modela_id = 'CD' THEN 'RPFX' WHEN...

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...

Why aren't my commandline arguments being read?

I am calling this in my program: std::string gameDirectory = ""; for (int i = 1; i < argc; i++) { if (argv[i] == "-game") gameDirectory = argv[i + 1]; } if (gameDirectory == "") exit(0); With the commandline argument -game demo and it refuses to set the gameDirectory. Any...

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.

Multiple parameters of a function

How to give break (== ' ') xxs multiple boolean parameters without changing the definition? Or that is inevitable. For instance break (== (' ' || '\t' || '\n')) xss foldl and foldr are one way, but here they are not applicable, or at least I haven't been able to...

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...

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...

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...

How to return double[] in jni input argument

In my Java code I have defined the following function signature: public native boolean getData( double [] data ); In my C++ code I'd like to populate the double array data to return back to Java, and the returned boolean from the function will indicate whether the data was set...

Pass symbol as Arguments

I have a already defined and working method as, render_format(doc,host,table_info) I had this method called at some location wherein I passed the arguments as, render_format("Daily Transactions in POS", {:doc => xml,:schema_name => "#{schema_name}",:store_code => "#{store_code}"}, :sales_log => "#{sales_log}") This worked just fine. Now I have to call this method as,...

Practical Reasons to use C# “named arguments”

I find this feature "named arguments" from C# to be really weird because I see two flaws from it. The book says "named arguments give you the "ability to pass arguments in any order". Two flaws I think is a problem for this C# feature: It violates "information hiding" in...

Passing arguments to a perl package while using it

it is possible to pass some arguments while using a package, for example: use Test::More tests => 21; I wasn't able to find any valuable documentation about this featue. Are there any pros and cons of passing such arguments? Best, R....

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...

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...

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,...