I'm trying to convert hexadecimal number to hexadecimal number presentation.
for example is below.
CL-USER> (foo 0D)
#x0D
Should i use macro function?
0D is a symbol (by default). Get its name with SYMBOL-NAME as a string. Use PARSE-INTEGER with :RADIX 16 to get the number.
If you don't have any reason for it, representing hex numbers as symbols is nothing I would do.
Are you saying that you want to format a number as a hexadecimal string? If so, you would want something like this: (format nil "~x" #x0D)
As phrased your question makes no sense. There is no such thing as a "hexadecimal number"; "hexadecimal" is the name of a number-presentation system. In your example, the input appears to be a symbol, as Rainer says, but not every such "hexadecimal" is a symbol. Presumably you want the output of (foo 10) to be #x10, and here the input is a number. So if the input is interpreted by the Lisp reader as a (base-10) number, then it should be converted to the number you would get if reread base 16.
Another point that Rainer overlooked is that if 0D is understood as a symbol, then (foo 0D) would cause an UNBOUND-VARIABLE error. You would have to write (foo '0D) to make 0D an input to foo.
On the output side, I don't think there is any native Lisp object that prints as "#x..." . If you want numbers to print in base 16, then you bind print-base to 16, but you won't see any sharpsign-x in front of it.
That suggests a somewhat different approach to your problem. We define a new datatype that does print starting with #x, and have foo construct such an object:
(defstruct (pseudo-hex (:print-object pseudo-hex-print))
thing)
(defun pseudo-hex-print (h srm)
(format srm "#x~a" (pseudo-hex-thing h)))
(defun foo (x)
(make-pseudo-hex :thing x))
Now we get the following:
cl-user(162): (foo 38)
#x38
cl-user(163): (foo '0D)
#x0D
I have a funny feeling this is not what Rafael was asking!
Related
How would I do something like the following in scheme?
printf("I went to the park at %d with %s", 4, "Bob");
The closest I have right now is:
(define TIME 4)
(define NAME "Bob")
(display "I went to the park at ") (display TIME) (display " with ") (display NAME) (display ".")
You can't do this in standard Scheme. Many Scheme implementations have a format procedure that is modeled on the Common Lisp format. For example, Chez Scheme has a pretty complete implementation of format, and also printf which is just a wrapper around format. I am so used to using format that I never think to use printf in lisps:
> (format #t "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
> (printf "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
Here format sends the output to the current output port when the first argument is #t; printf automatically sends output to the current output port. Common Lisp style format directives are prefixed with a tilde (~). The ~A, or aesthetic, directive prints objects in human-readable form, and is what you want most of the time. There are other directives for formatting numbers; I added the ~% directive, which emits a newline. Your original example did not include a newline, and printf, at least in C, does not add a newline at the end of output (ordinarily this is desirable). The format procedure should allow much more control over results than the mother of all printfs, namely C's fprintf.
The specific facilities for printing formatted output will depend on the implementation, but Chez Scheme, MIT Scheme, Gauche Scheme, and Guile all implement format. Chicken Scheme implements format, and also implements printf, fprintf, and sprintf which all use the same format directives as format. Racket has a host of formatted output procedures, including format, printf, and fprintf; all of these use Common Lisp style format directives, too.
You will have to consult the documentation of a specific implementation to understand which format directives are supported and how they work; the Chez Scheme documentation contains some information, but suggests consultation of the Common Lisp HyperSpec for complete documentation.
There are also SRFI-28 (Basic Format Strings) and SRFI-48 (Intermediate Format Strings) which provide some of this functionality to implementations that support them.
It really depends on what Scheme interpreter you're using. For example, in Racket you can use printf for a similar effect:
(printf "I went to the park at ~a with ~a" 4 "Bob")
=> I went to the park at 4 with Bob
Check the documentation for more formatting modifiers.
I need to generate a space-padded string with a variable string length. The not-so-clever solution that works involved nesting of format:
(format nil (format nil "~~~d,,a" 10) "asdf")
Now, I wanted to make it a bit more clever by using format's ~? for recursive processing. I would expect that something like this should do what I want:
(format nil "~#?" "~~~d,,a" 10 "asdf")
but what I get is just the formatting string, i.e. ~10,,a, not the padded asdf string. Perhaps I misunderstood the word 'recursive' here, but I would expect that having formed the inner format string, CL should proceed to actually use it. Am I missing something?
Variable arguments to format directives
FORMAT allows you to use v as an argument to a directive in the control string to pop arguments from the argument list.
CL-USER> (format nil "~va" 10 "asdf")
"asdf "
There may be multiple vs used.
CL-USER> (format nil "~v,,,va" 10 #\- "asdf")
"asdf------"
Recursive processing with ~?
The recursive processing directive is meant for embedding a different "call" to FORMAT inside a control string. For example, a function to prompt for a yes or no answer might be implemented with it.
(defun y-or-n-prompt (control-string &rest args)
(format t "~&~? [y/n]: " control-string args)
;;...
)
The caller can now format a prompt with this as they would with FORMAT without having to worry about the details of what the prompt should look like to the user (adding a new line at the beginning or the [y/n]: prompt at the end).
CL-USER> (y-or-n-prompt "foo ~d bar" 12)
foo 12 bar [y/n]:
NIL
The result of ~? will not be processed by FORMAT, so it cannot be used to build a control string. In general, building control strings at run time is a bad idea, because it's error prone (for example, you must escape any unwanted tildes in the string) and prevents the implementation from processing the control string at compile time.
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.
(Though this is indeed simple question, I find sometimes it is common mistakes that I made when writing Scheme program as a beginner.)
I encountered some confusion about the define special form. A situation is like below:
(define num1
2)
(define (num2)
2)
I find it occurs quite often that I call num2 without the parentheses and program fails. I usually end up spending hours to find the cause.
By reading the r5rs, I realized that definition without parenthesis, e.g. num1, is a variable; while definition with parenthesis, e.g. num2, is a function without formal parameters.
However, I am still blurred about the difference between a "variable" and "function".
From a emacs lisp background, I can only relate above difference to similar idea as in emacs lisp:
In Emacs Lisp, a symbol can have a value attached to it just as it can
have a function definition attached to it.
[here]
Question: Is this a correct way of understanding the difference between enclosed and non-enclosed definitions in scheme?
There is no difference between a value and a function in Scheme. A function is just a value that can be used in a particular way - it can be called (as opposed to other kinds of value, such as numbers, which cannot be called, but can be e.g. added, which a function cannot).
The parentheses are just a syntactic shortcut - they're a faster, more readable (to experts) way of writing out the definition of the name as a variable containing a function:
(define (num)
2)
;is exactly the same as
(define num
(lambda () 2) )
The second of these should make it more visually obvious that the value being assigned to num is not a number.
If you wanted the function to take arguments, they would either go within the parentheses (after num, e.g. (num x y) in the first form, or within lambda's parentheses (e.g. (lambda (x y)... in the second.
Most tutorials for the total beginner actually don't introduce the first form for several exercises, in order to drive home the point that it isn't separate and doesn't really provide any true functionality on its own. It's just a shorthand to reduce the amount of repetition in your program's text.
In Scheme, all functions are values; variables hold any one value.
In Scheme, unlike Common Lisp and Emacs Lisp, there are no different namespaces for functions and other values. So the statement you quoted is not true for Scheme. In Scheme a symbol is associated with at most one value and that value may or may not be a function.
As to the difference between a non-function value and a nullary function returning that value: In your example the only difference is that, as you know, num2 must be applied to get the numeric value and num1 does not have to be and in fact can't be applied.
In general the difference between (define foo bar) and (define (foo) bar) is that the former evaluated bar right now and foo then refers to the value that bar has been evaluated to, whereas in the latter case bar is evaluated each time that (foo) is used. So if the expression foo is costly to calculate, that cost is paid when (and each time) you call the function, not at the definition. And, perhaps more importantly, if the expression has side effects (like, for example, printing something) those effects happen each time the function is called. Side effects are the primary reason you'd define a function without parameters.
Even though #sepp2k has answered the question, I will make it more clearer with example:
1 ]=> (define foo1 (display 23))
23
;Value: foo1
1 ]=> foo1
;Unspecified return value
Notice in the first one, foo1 is evaluated on the spot (hence it prints) and evaluated value is assigned to name foo1. It doesn't evaluate again and again
1 ]=> (define (foo2) (display 23))
;Value: foo2
1 ]=> foo2
;Value 11: #[compound-procedure 11 foo2]
1 ]=> (foo2)
23
;Unspecified return value
Just foo2 will return another procedure (which is (display 23)). Doing (foo2) actually evaluates it. And each time on being called, it re-evaluates again
1 ]=> (foo1)
;The object #!unspecific is not applicable.
foo1 is a name that refers a value. So Applying foo1 doesn't make sense as in this case that value is not a procedure.
So I hope things are clearer. In short, in your former case it is a name that refers to value returned by evaluating expression. In latter case, each time it is evaluated.
I had to create a simple scheme program that outputs the contents of a binary tree. I managed to complete the program but it outputs all the quotes with it. How do I get rid of them?
(define bintree
'(interior-node
'foo
(interior-node 'bar (leaf 26) (leaf 12))
(interior-node 'baz (leaf 11)
(interior-node 'quux (leaf 117) (leaf 14)))))
(print-bintree bintree) returns ('foo ('bar 26 12) ('baz 11 ('quux 117 14)))
I want it to return (foo (bar 26 12) (baz 11 (quux 117 14))) without the ' mark on it.
It's hard to say without seeing the whole program (in particular, the definition of print-bintree), but it looks like a simple misunderstanding about how the quote works.
In particular, a quote before an open paren means that the contents of the parens are interpreted in a simple "data language", where sequences of characters are interpreted as symbols rather than variables.
To see what I mean, let's try evaluating some simple expressions
(zippy tong)
... produces some error about zippy and tong being undefined.
Now, try this:
'(zippy tong)
The result is going to depend a bit on your printer, but it will produce the same thing as
(list 'zippy 'tong)
That is, the leading quote means that zippy and tong are interpreted as symbols, rather than as variables.
In your code, you write:
'(interior-node 'foo ...)
The problem here is that you're using a quote when you're already inside a quoted expression. This isn't doing what you want. In particular, it will produce something equivalent to
(list 'interior-node (list 'quote 'foo) ...)
So, without getting any further into the magic of quote, it will probably suffice to remove the quotes from the 'foo, 'bar, etc. inside your definition of bintree.