How to replace variable value inside cons cell in racket - scheme

I would like to do something like this
(cons '(someword,string->symbol somevarname) (restoflist))
but somevarname is never replaced by its value.
I thought this was possible?

Quote makes literal lists. To make a list dynamically at runtime, you can also use quasiquote and unquote. For your case, it looks something like the following (assume somevarname is either locally or globally bound):
(cons `(someword ,(string->symbol somevarname)) (restoflist))

It is, but because you quoted the expression containing string->symbol, it never got evaluated. I'd try to show the right way to get what you want, but it isn't clear just what that is.
Based on your comment (and ignoring the comma), it seems that you would want:
(cons (list 'someword (string->symbol "somevarname")) restoflist)

Related

Why (car (1 2)) from The Little Schemer does not work in DrRacket?

I have been reading the first chapter of "The Little Schemer". The problem is, some examples work in DrRacket like (eq? "foo" "foo") and some don't like (car ("a" "b")) or (cdr ("a" "b")) because of
application: not a procedure;
expected a procedure that can be applied to arguments
given: "a"
arguments...:
Can you point me why these example do not work?
These examples don't work because they're not legal Scheme. I'm not familiar with the book, but it may be the case that it has been typeset in a way which may make it slightly hard to transcribe examples from it without the mistake you've made. To see why they're not you need to think about how the system evaluates things. Here is a simple-minded and partial description of how that might work (real implementations do something much hairier than this, and this description is partial not least because it contains no explanation for how we get the bindings of things at all).
To evaluate something:
is it something special like a string or a number or something like that, in which case its value is just itself;
is it a symbol, in which case look up the binding for that symbol and that is the value;
is it a compound form like (foo ...)? If it is, then –
look at its first element: is it a special magic thing we know about? If it is then do an appropriate special thing (see below);
otherwise evaluate all of the elements of the compound form in any order you like – the value of the first element should be a function, and the value is the result of applying this function to the values of the remaining elements.
So we can use these rules to try to evaluate (car ("a" "b")).
the form is a compound form, so we need to take the compound form case;
car is not any kind of special thing, so we don't hit that case;
so, evaluating the elements of the form (I'll do it left to right for simplicity) –
car is a symbol, so look up its value which is a function;
("a" "b") is a compound form, and its first element is not special –
evaluate its elements, both of which are literal strings whose value is themselves;
and now try to apply the value of first element to the values of all the others, and fail, because it is a string not a function.
OK, so this can't work. To make it work we need to go back and look at a case in the evaluation rules: when evaluating a compound form we sneak a look a the first element to decide if it is some special magic thing we know about and in that case we do something special. There are a small number of such special magic things: the only one that we care about here is quote. The special rule for this is:
if we see a compound form whose first element is quote, which will look like (quote ...), then –
it should have exactly two elements, so it should look like (quote <x>) for some <x>;
the value of the form is <x> with no further attempt to evaluate <x>.
So, for instance:
the value of (quote x) is the symbol x;
the value of (quote (1 2 3)) is the list (1 2 3);
the value of (quote "x") is the string "x" (you don't need quote in this case, since strings already evaluate to themselves by the very first rule above, but it does not hurt).
So to go back to the form we wanted to evaluate, what we actually need is (car (quote ("a" "b"))). When evaluating this:
the form is a compound form, so we need to take the compound form case;
car is not any kind of special thing, so we don't hit that case;
so, evaluating the elements of the form (I'll do it left to right for simplicity) –
car is a symbol, so look up its value which is a function;
(quote ("a" "b")) is a compound form –
its first element is special, since it is quote;
so use the rule for quote and the result is ("a" "b");
now apply the value of car to ("a" "b"), and the result is "a".
So then there is one more trick: (quote <x>) occurs a lot, so there is a special syntax for it, which is a single ': 'x reads identically to (quote x). This just makes source code less verbose. So this gives the final form of the working version of what you're trying to do:
(car '("a" "b"))
Finally, the reason Lisps need quote is an interesting thing to think about, but off-topic for this answer.

Get variable value with a string in scheme

How can we get variable value with a string in scheme language as we can achieve this in Common Lisp:
> (defvar s 3)
> S
> (symbol-value (intern "S"))
> 3
I am accessing a parameter of parent function from the closure.
EDIT: I have found this solution, but I can't use eval because it evaluates at top level. Searching for alternatives.
(eval (string->symbol "s"))
EDIT 2: I have found that Common lisp code also try to find symbol in global space. So this question is basically for both Lisps(Common Lisp, Scheme).
Don't do that!
Variables are for when you know the variable at compile time. In that case it is never a string. You can still reason about strings in compile time but your code also needs to have a relation with the name for it to be interesting. When you use eval or other forms that evaluate structure and compile/run data in runtime you are probably not doing it right (but not always. I've in my 20 year career used eval intentionally in production code twice)
If you want to store values you use a data structure. An assoc would mimic a dynamic environment. You can also use a hash with a level indicator if the size is harmless.
You can't do what you want to do and in fact it is a confused thing to want to do.
Here's why what you are trying to do is confused. Consider how a Lisp system for which it was possible to do what you wanted would work. In particular consider something like this:
(define (foo a name)
(let ([b 10])
(display (get-value name))
(* a b)))
Where get-value is meant to be how you get the binding of whatever something is.
So, if I call (foo 10 "b") it should print 10 and return 100.
But wait: b is a compile-time constant in this code. Any compiler worth its salt is going to immediately turn this into
(define (foo a name)
(display (get-value name))
(* a 10))
And now there is no binding of b.
So there are two options here: what you want to work works and it is impossible to ever write a reasonable compiler for Scheme, or what you want to work doesn't work, and it is.

How to determine if a variable exists in Chicken Scheme?

Is there a way in Chicken Scheme to determine at run-time if a variable is currently defined?
(let ((var 1))
(print (is-defined? var)) ; #t
(print (is-defined? var)) ; #f
EDIT: XY problem.
I'm writing a macro that generates code. This generated code must call the macro in mutual recursion - having the macro simply call itself won't work. When the macro is recursively called, I need it to behave differently than when it is called initially. I would use a nested function, but uh....it's a macro.
Rough example:
(defmacro m (nested)
(if nested
BACKQUOTE(print "is nested")
BACKQUOTE(m #t)
(yes, I know scheme doesn't use defmacro, but I'm coming from Common Lisp. Also I can't seem to put backquotes in here without it all going to hell.)
I don't want the INITIAL call of the macro to take an extra argument that only has meaning when called recursively. I want it to know by some other means.
Can I get the generated code to call a macro that is nested within the first macro and doesn't exist at the call site, maybe? For example, generating code that calls (,other-macro) instead of (macro)?
But that shouldn't work, because a macro isn't a first-class object like a function is...
When you write recursive macros I get the impression that you have an macro expansion (m a b ...) that turns into a (m-helper a (b ...)) that might turn into (let (a ...) (m b ...)). That is not directly recursive since you are turning code into code that just happens to contain a macro.
With destructuring-bind you really only need to keep track of two variables. One for car and one for cdr and with an implicit renaming macro the stuff not coming from the form is renamed and thus hygenic:
(define-syntax destructuring-bind
(ir-macro-transformer
(lambda (form inject compare?)
(define (parse-structure structure expression optional? body)
;;actual magic happens here. Returns list structure with a mix of parts from structure as well as introduced variables and globals
)
(match form
[(structure expression) . body ]
`(let ((tmp ,expression))
,(parse-structure structure 'tmp #f body))))))
To check if something from input is the same symbol you use the supplied compare? procedure. eg. (compare? expression '&optional).
There's no way to do that in general, because Scheme is lexically scoped. It doesn't make much sense to ask if a variable is defined if an referencing an undefined variable is an error.
For toplevel/global variables, you can use the symbol-utils egg but it is probably not going to work as you expect, considering that global variables inside modules are also rewritten to be something else.
Perhaps if you can say what you're really trying to do, I can help you with an alternate solution.

basic Clojure syntax

Let's say I have a macro, inside the macro I have this let:
let[
elements# //stuff//
#newlist (for [e# elements#] (if (number? e#) (**add e# to #newlist**)))
]
Since I am having a really hard time finding proper information on the really simple Clojure stuff, I'm here to ask: what do I need to do to accomplish this task above? I think it should be possible to do this but I don't know the most crucial part!
It looks like you're trying to create a list called newlist which contains all those elements of elements that are numbers. If so, you can just use the filter function like this:
(let
[elements whatever
newlist (filter number? elements)]
do-stuff-with-newlist)
filter takes a predicate function and a list and returns a new list that contains those items for which the predicate returns a true result.
Note that your initial idea of adding to a list inside a for-loop would not work because lists are immutable, so you can not add to them in-place. You could re-assign a variable holding the list inside a for loop (something like (set! my-list (cons e my-list)), but that would not be idiomatic Clojure code. It would also create the list in reverse.

Quotation in Scheme

Following is a exercise from SICP. I couldn't figure it out on my own. Can some why help me understand?
Type following code into interpreator:
(car ''abracadabra)
And it print out 'quote'. Why?
As gimpf said, 'abracadabra = (quote abracadabra). You can verify this by typing ''abracadabra to the REPL, which will print (quote abracadabra).
Because ''abracadabra is really (quote (quote abracadabra)). In Scheme, the rule is: evaluate all the parts of the s-expression, and apply the first part to the rest of the parts.
"car" and "quote" are symbols in the below. #car and #quote are the functions they refer to.
If you take
(car (quote (quote abracadabra)))
and evaluate the parts, you get
(#car (quote abracadabra))
Then, apply the first part (the car function) to the second part (a list of two symbols).
quote
And you get just the symbol "quote".
Just remember, to figure out what happens in Scheme, evaluate the parts and apply the first to the rest. If you evaluate quote, you get the stuff inside. The only confusing part is that some primitives (number and strings) evaluate to themselves.

Resources