variables,binding,scheme,lisp,common-lisp , How can I modify function bindings in Common Lisp?

How can I modify function bindings in Common Lisp?


Tag: variables,binding,scheme,lisp,common-lisp

Here is something you can do in Scheme:

> (define (sum lst acc)
    (if (null? lst)
        (sum (cdr lst) (+ acc (car lst)))))
> (define sum-original sum)
> (define (sum-debug lst acc)
    (print lst)
    (print acc)
    (sum-original lst acc))
> (sum '(1 2 3) 0)
> (set! sum sum-debug)
> (sum '(1 2 3) 0)
(1 2 3)
(2 3)
> (set! sum sum-original)
> (sum '(1 2 3) 0)

If I were to do the following in Common Lisp:

> (defun sum (lst acc)
    (if lst
        (sum (cdr lst) (+ acc (car lst)))
> (defvar sum-original #'sum)
> (defun sum-debug (lst acc)
    (print lst)
    (print acc)
    (funcall sum-original lst acc))
> (sum '(1 2 3) 0)

Now how can I do something like (setf sum #'sum-debug) that would change the binding of a function defined with defun?


Because Common Lisp has a different namespace for functions, you need to use symbol-function or fdefinition.

CL-USER> (defun foo (a)
           (+ 2 a))
CL-USER> (defun debug-foo (a)
           (format t " DEBUGGING FOO: ~a" a)
           (+ 2 a))
CL-USER> (defun debug-foo-again (a)
           (format t " DEBUGGING ANOTHER FOO: ~a" a)
           (+ 2 a))
CL-USER> (foo 4)
CL-USER> (setf (symbol-function 'foo) #'debug-foo)
CL-USER> (foo 4)
CL-USER> (setf (fdefinition 'foo) #'debug-foo-again)
CL-USER> (foo 4)


BooleanToVisibilityConverter works on Textblock and not on UserControl

I'm working on a windows phone project. There is something i don't really understand about my xaml. Here it is: <Page x:Class="CitiBox.MainPage" xmlns="" xmlns:x="" xmlns:d="" xmlns:mc="" xmlns:converters="using:CitiBox.Converters" xmlns:views="using:CitiBox.Views" mc:Ignorable="d" Background="{ThemeResource...

PHP Define var = one or other (aka: $var=($a||$b);)

Is there a way to define a php variable to be one or the other just like you would do var x = (y||z) in javascript? Get the size of the screen, current web page and browser window. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight...

gnuplot - get errors on fit parameters, get fit output values as variables, print variable to screen

Initial Question (Partially Answered) I am using gnuplot's fitting routines to fit a function to some data, and extract a "characteristic decay time constant". (I call this parameter d in my fitting function.) I have used the script code set fit quiet to prevent reams of text being printed to...

Bind Control to Two properties

Using MVVM pattern and WPF, I would like to bind my controls to two properties. Let's say I have a label that is bind to property on VM1 and I would like to bind it as well to the property on VM2 to send received value from VM1 to VM2....

VBA SUM Variable Range

I want a code to sum the Variable rows up if certain condition is met. e.g. If A12 is numeric and B12 is empty then insert a fomula in cell C12 to sum C3:C11. Then perform the same action at C22 and C30. The problem I have is don't...

WPF: static INotifyPropertyChanged event

This is my model: class Person : INotifyPropertyChanged { public static int Counter; public string _firstName; public string _lastName; public event PropertyChangedEventHandler PropertyChanged; public string FirstName { get {return _firstname; } set { _fileName = value; NotifyPropertyChange("FirstName"); } } public AddPerson(Person person) { Counter++; } } I have this NotifyPropertyChange...

calling string as variable in python

I created a class called SignalParam in python containing different properties (frequency, voltage, time, etc) I would like to create many instances of this type vars()['Segment'+str(segment_number)] = SignalParam() this line is working and i can create variables "Segment1", "Segment2", .... My question is: i would like to call those variabes...

Delphi - Use a string variable's name in assignfile()

Is it possible to use a variable in the assignfile command? Eg. f : Textfile ; sFile : string ; {contains 'MyFile.txt' as content} ... cFileDir = 'C:\Users\User\Desktop\Data Engine\Data\Country' ; ... Assignfile(f, cFileDir + '\' + sFile) ; ... I appreciate your help very much. if it's unclear I'll edit...

PHP / JavaScript: How to pass variable from one page to another

I am new to PHP and hope someone can help me with this. I have a page (index.php) where users can select a language. If no language is selected than the page URL is just index.php which defaults to English. If they select a language than the page gets reload...

Java: Assigning a variable its current value?

If I have a string that is currently empty String s = ""; and reassign it s = ""; is it bad it I don't do it like this? if(!s.isEmpty()){ s = ""; } or will the compiler pick up on it and optimize for me?...

Problems with Flash 8 (AS2), Timelines, and Variable Scopes

Okay, so trying to not post 5 pages of information, I'll start with the following: In a movie clip, I have 3 keyframes. I'm trying to edit a textbox on each frame, but I've found previously that only the text box in the current frame is accessible. In an attempt...

PS pipe WorkingSet as variable

I have this which gives me the WorkingSet memory usage I'm after: $mem=Get-Process spiceworks | Select-Object Name,@{Name='WorkingSet';Expression={($_.WorkingSet/1KB)}} But I'm looking to only have the actual amount as the variable so I can then work with that to monitor it. I want to set it so it alerts me if it...

Polymer 1.0 data binding not working

I have the following polymer element: The value of navigator.currentStep is not updating after someMethod is called. <dom-module id="m"> <template> Navigator step = <span>{{navigator.currentStep}}</span> </template> </dom-module> Polymer({ is: 'm', ready: function() { this.navigator = new Navigator(1); console.log(this.navigator.currentStep); // 1 }, someMethod: function() {; console.log(this.navigator.currentStep); // 2 } }); Output...

Compiler modifying a variable without adressing it

In my program I found that when asssigning a variable to another, modifying the first one, also modifies the second. Example: using System; using System.Collections.Generic; using System.Windows.Forms; namespace Dict_test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void TestButton_Click(object sender, EventArgs e) { Dictionary<string,...

If a = b, what happens if each value changes respectively?

What happens if you change the variable b, or what if you change a. What does the order have to do with anything. I know count = count + 1 but the two variables is messing up my brain. b = 7; a = 7; a = b; a +=...

How to extract first letters of dashed separated words in a bash variable?

I would like to extract the first letter of dashed separated words value of my bash variable, like this: MY_TEXT=this-is-my-custom-text I would like to create a second variable like this: MY_INITIALS=timct...

Batch file %%i was unexpected at this time

I am trying to get a patch file to set a variable to the number of instances that are running for a particular executable but am getting this error: %%i was unexpected at this time Here is my code: for /f %%i in ('wmic process where name="chrome.exe" ^| find "chrome.exe"...

Get variable *value* instead of variable itself

Look at this code: <button id="button">Test</button> <button id="button2">Test</button> <script> button = document.getElementById("button"); button2 = document.getElementById("button2"); var x = 5; button.onclick = function() { alert(x); } var x = 10; button2.onclick = function() { alert(x); } </script> When I click on both of the buttons, I get 10 as result. But...

How do I use the Find function with a variable term, for example Run1, Run2, RunX

Cells.Find(What:="Run:1", After:=Cells(1, 1), _ LookIn:=xlValues, LookAt:=xlPart, _ SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) This is the code that I want to use, but I would like to loop it to find Run:1, Run:2, Run:3... Etc..., Is there a way to add a variable in a reference to find "Run:X"?...

How can i make this CommandParameter work?

I've been learning WPF in college this semester but there are still some things I do not fully understand. I have the following code: <UserControl x:Class="Reversi.SquareControl" xmlns="" xmlns:x="" xmlns:mc="" xmlns:d="" mc:Ignorable="d" d:DesignHeight="48" d:DesignWidth="48"> <Button Command="{Binding Place}"...

How can I use a variable to get an Input$ in Shiny?

I am new to R and I am creating a shiny application to read a csv and filter data. I am reading the csv file, then creating dropdowns with a loop using the column names and the unique values: output$dropdowns <- renderUI({ if (is.null(x())) { return(NULL) } lapply(1:ncol(x()), function(i) {...

Is there any way of protecting a variable for being modified at runtime in C?

I was wondering if there is any way of protecting a variable for being modified once initialized (something like "constantize" a variable at runtime ). For example: #include <stdio.h> #include <stdlib.h> int main(void) { int v, op; scanf( "%d", &op ); if( op == 0 ) v = 1; else...

XSLT filePath with document as variable

I try to use a variable in the filePath, but it isn't working: BodyPart filePath="C:\\FileOutEmail\\($vpDocNr).xml" content-type="" content-id="" content-disposition="" multipart-type="" I also tried with the whole path in a variable without results: BodyPart filePath='$bestand' content-type="" content-id="" content-disposition="" multipart-type="" Is this possible, what is the right syntax?...

How do I provide a collection of elements to a custom attached property?

I found a few examples online, and a few questions and answers here, but I just can't get it to work. I need a custom attached property that can take one or more target elements. For example... <ListView> <dd:MyDragDrop.DropBorders> <Binding ElementName="brdOne"/> <Binding ElementName="brdTwo"/> <Binding ElementName="brdThree"/> </dd:MyDragDrop.DropBorders> </ListView> I've also had...

jQuery - Increase integer by using arrays content as the variable name

Okay. This might be a little bit difficult to explain. Let's just say I have three variables in JavaScript window.seconds = 0; window.minutes = 0; window.hours = 0; and also three anchor tags in HTML <a id='seconds_plus' href=''>Increase seconds</a><br> <a id='minutes_plus' href=''>Increase minutes</a><br> <a id='hours_plus' href=''>Increase hours</a><br> Each time a...

String concatenation not working in HTML declaration of TABS through PHP variables [closed]

The below code is not showing similar results as other one : <?php $week = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); $k=0; while ( $k<= 6) { $t=$k+1; echo "<li>"; echo "<a href=#panel-".$t." data-toggle='tab'>".$week[$k]; echo "</a></li>"; $k+=1; } $a=1; echo '<div class="tab-content"> <div class="tab-pane" id="panel-"'.$a.'> <div class="alert alert-info" role="alert"> <a href="#" class="alert-link">'.$week[$a].'Bazaars</a> </div>'; ?>...

Having two arrays in variable php

i've this code, i'm trying to explode my date e.g "04 June 2015" to have the day and the month in other 2 variables, but i have all in a method, with an array, is it possible, my code doesn't work, it writes "Array[0]" why? while ($i < $number) {...

SQL Multiple LIKE Statements

I'm currently working on a report that shows me all post codes covered by our sales team. Each team covers over 100 post codes. What i would like to do is create a report that brings back the clients within the post code. Currently my code looks like this. SELECT...

How to get value from property in BeanShell (jmeter)

I have got several thread groups. I want to use variable from the first group. In second group this var should be used in BeanShell. So: in first thread group I created BeanShell Assertion with this code: ${__setProperty(erroriden, ${erroriden1})}; In second thread group I have BeanShell pre-processor. If has line...

subtracting from multiple variables at a time

So recently I've ben interested in learning python, and I got the "Think python" last Christmas. Unfortunately I haven't had the time to really get into it because of my exams. Even though I the book was written for python 2 I decided to use python 3.4.3 anyway. This does...

Javascript: Resetting variable value created by form

I've created a form whereby the user enters details which are stored in variables or calculated depending on user entry. When clicking the button, a message will be displayed showing a message with the cost variable. The form clears but the message remains. The problem I have is that the...

Very weird behavior when using “var” keyword in an ajax request

I've been worrying about this for a while and I can't realize what's really happening. Explanation in code comments. There are 2 versions of an application, one of them throws weird results and the second one does the expected work. var id = "test1"; $.post("", {"data": "data"}, function(a) { alert(id);...

Maya MEL variables declaration and initialization

Is it obligatory in MEL to initialize variables and especially strings when you declare them? I know that it is not necessary to initialize string arrays: string $buffer[]; $buffer[0] = "abc"; But what about strings and other variable types? Is it acceptably: string $str; $str = "abc"; Or should always...

Undefined local variable post

I write this code: <% @user.posts.each do |post| %> <%= render 'post', locals: { post: post, user: @user} %> <% end %> Then in _post.htm.erb I write follow code: <div class="post-title"> <img src="<%= @user.avatar.url%>" class="img-rounded post-image"> <h4 id="post-name"><%= @user.first_name + ' ' +@user.last_name %> </h4> <div id="post-date"><%= post.created_at.strftime('%d %b -...

MvvmCross RaisePropertyChanged and dot (.) binding

I have a custom binding that accepts entire view model: public class TextViewGroupInfoBinding : BaseBinding<TextView, GroupViewModel> { private IMvxAndroidCurrentTopActivity CurrentTopActivity { get { return ServiceLocator.Current.GetInstance<IMvxAndroidCurrentTopActivity>(); } } public TextViewGroupInfoBinding(TextView androidControl) : base(androidControl) { } public override MvxBindingMode DefaultMode { get { return MvxBindingMode.OneWay; } } protected override void SetValueToView(TextView control,...

Where are the local variables of an Android app stored?

The Dalvik Virtual Machine (DVM) has a register-based architecture, as opposed to the Java Virtual Machine (JVM) which is stack-based. So I assume that the local variables of an Android app are stored in the registers. Am I correct? If not, please correct me. If yes, what kind of memory...

MySQL multi SELECT query into form and then UPDATE

What i am trying to accomplish is Getting data from MySQL database into a table only containing rows where a user forgot to log in or out(done) Change the data in the table (done) Click submit and it updates all the data in the table into the MySQL database I...

php form mail function

I am using a mail function to mail it to my email adress, but i want it to send me a message with variables in it. (I have tried to concatenate it with concatenation point, but it doesn't seem to work, or I did not use it right) The code:...

Change ImageBrush Imagesource programmaticaly with conditions (WPF)

maybe that question was asked 100 times but can you help please I searched everywhere but can't find a normal answer. I got such xaml <Window x:Class="Imagebind.MainWindow" xmlns="" xmlns:x="" Title="MainWindow" Height="350" Width="525" Background="#FF3F3B51"> <Window.Resources> <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}"> <Setter Property="FocusVisualStyle"> <Setter.Value> <Style>...

Run 3 variables at once in a python for loop.

For loop with multiple variables in python 2.7. Hello, I am not certain how to go about this, I have a function that goes to a site and downloads a .csv file. It saves the .csv file in a particular format: name_uniqueID_dataType.csv. here is the code import requests name =...

Div with a simple variable height

So, I want to make a div that has the height of a value I'm going to get from my database. To make it better do understand, the value is a the number of times a client has bought in the website. I'm thinking of a way to make my...

SQL Repeated Condition in Two Tables

I am a beginner to SQL, and I am having trouble getting rid of repeated code. I have a condition "AccountId=20" that I use twice in a SQL query. The SQL looks something like: DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountId=20); DELETE FROM Table_B WHERE...

How to check for a variable name using a string in Python?

For simplicity I'm try to do this. spam = [1,2,3] stuff = [spam] x = input() if x in stuff: print(True) else: print(False) As it runs: >>> spam False Of course it doesn't print 'True' because the string 'spam' is not equal to the variable spam. Is there a simple...

Why is interface variable instantiation possible?

As far as I know, interfaces cannot be instantiated. If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible? Interface: public interface IDynamicCode<out TCodeOut> { object DynamicClassInstance { get; set; } TCodeOut Execute(string value = "");...

Swift Reverse Geocoding using the Data

I am successfully getting the current address details based on my location. It printlns perfectly. What is throwing me is how I extract the data from this call. I have tried passing, say the ZIP/Postcode, as local and even global variables but with no joy. The data only seems to...

Binding imperatively

Is there a way to set up bindings imperatively. An example use case: var el2 = new MyElement(); el2.myProp = this.$.anotherElement.anotherProp That won't setup a binding, it just assigns the value or object. I'd like to find a way to do something like: el2.myProp.bindTo(this.$.anotherElement.anotherProp) Possible?...

read variable excel data into variant with the same format

I'm currently writing a Macro for Excel. First I want to read my variable settings from row 20 from my sheet "Filter" into my variable "test": ' Define Last Column with a value LastCol = Sheets("Filter").Cells(20, Sheets("Filter").Columns.Count).End(xlToLeft).Column Col_Letter = Split(Cells(1, LastCol).Address(True, False), "$")(0) ' Read Data into variable test =...

Is [ $var ] an acceptable way to check for variables set/empty in bash?

I wrote some bash before reading this popular question. I noticed the way I was doing things doesn't show up in any of the answers so I was curious if there is a danger/bug to my logic that I am not seeing. if [ ! $1 ] || [ $2...

Assign the value from a text field into an int variable to do some math with other variables and then return it?

The code showing here assigns the value of an variables to the text field I want to do the opposite of that. _Initial.text = [NSString stringWithFormat:@"%f", init]; The opposite of the code above. Please help...

Call known function (with parameters) in class whose name is defined by string variable

I have a bunch of classes of various names and each has a performLogic function that accepts a number of preset parameters (always the same): public final class DoSomeAction extends SetupAction { public void performLogic(param1, param2... I want a way where I can call it like this: String actionName =...