It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to write a program in LISP to get a string from the user and return the string formed by adding 1 to each char-code of the string. For example:
input: "hello123"
output: "ifmmp234"
I thought maybe I should convert the characters one by one to ASCII and then do what I want to do.
Any help with this will be so much appreciated..
Thanks
This is the code I developed. It gives me NIL in the output however. Can you help me with this:
(defun esi (n)
(setf m 0)
(loop (when (< m (length n))
(return))
(code-char (+ 1 (char-code (char n m))))
(+ 1 m)))
Look at the functions char-code and code-char.
EDIT: Regarding your code sample:
It seems that the input to your function should be a string. Name it such, e.g. string.
That (setf m 0) is setting a free variable. In this context, I must assume that m is never defined anywhere, so the behaviour is undefined. You should use, for example, let instead to establish a local binding. Hint: most looping constructs also give ways to establish local bindings.
The only exit out of your loop is that (return). Since it does not get any parameters, it will always return nil. You need to accumulate the new string somewhere and finally return it.
Functions in Lisp mostly do not modify their arguments. (+ 1 m) does not modify m. It just returns a value that is one greater than m. Likewise, code-char does not modify its argument, but returns a new value that is the character corresponding to the argument. You need to bind or assign these values.
That finishing condition is wrong. It will either terminate directly or, if the input string is empty, never terminate.
There are quite a few ways of doing what you want. Let's start with a function that returns a character one code-point later (there are some boundary issues here, let's ignore that for now).
(defun next-codepoint (char) (code-char (1+ (char-code char))))
Now, this operates on characters. Happily, a string is, essentially, a sequence of characters. Sequence operations should, in general, send you in the direction of the MAP family.
So, we have:
(defun nextify-string (string) (map 'string #'next-codepoint string))
Taking what's happening step by step:
For each character in an input stringm we do:
We convert a character to a code attribute.
We increment this
We convert it back for a character
Then we assemble all of these into a return value.
Related
I am studying an example of a program the takes a user input, stores in a string then prints two occurrences of the corrosponding character in upper or lower case. For example, input ABCdef would print aabbccDDEEFF.
I'm a little bit confused about the way the new string is declared, can anybody help explain what is happening.
char string[MAX_STRING_SIZE+1]; // MAX_STRING_SIZE is defined as 500 and +1 is for the NULL char to terminate string
char stringNew[MAX_STRING_SIZE*2+1]; // Here I do not understand *2+1
EDIT: Just after I posted this question I figured out the answer and realised it may not be useful to the stack overflow community but as the question had already been answered it would be rude to delete it.
In the event that an other member is interested in this specific question I have attempted to make it useful by editing the question title and summarising the answer.
As this program will print 2 occurrences of every character from the user input, the new string needs to be twice the size as the original string. By declaring the new string size with *2 you are simply multiplying the size by 2 thus doubling the size.
Very simple in hindsight, I hope this can be of use to somebody else.
No pointers are involved in that declaration. You're just declaring another array of chars that is twice the size of the first one + the extra byte that'll store \0.
It can't be a pointer because there are no identifiers between the square brackets. After the preprocessor will have done its job with the source file, that expression will actually become char stringNew[500*2+1];
This question already has an answer here:
Julia: invoke a function by a given string
(1 answer)
Closed 6 years ago.
I know that you can call functions using their name as follows
f = x -> println(x)
y = :f
eval(:($y("hi")))
but this is slow since it is using eval is it possible to do this in a different way? I know it's easy to go the other direction by just doing symbol(f).
What are you trying to accomplish? Needing to eval a symbol sounds like a solution in search of a problem. In particular, you can just pass around the original function, thereby avoiding issues with needing to track the scope of f (or, since f is just an ordinary variable in your example, the possibility that it would get reassigned), and with fewer characters to type:
f = x -> println(x)
g = f
g("hi")
I know it's easy to go the other direction by just doing symbol(f).
This is misleading, since it's not actually going to give you back f (that transform would be non-unique). But it instead gives you the string representation for the function (which might happen to be f, sometimes). It is simply equivalent to calling Symbol(string(f)), since the combination is common enough to be useful for other purposes.
Actually I have found use for the above scenario. I am working on a simple form compiler allowing for the convenient definition of variational problems as encountered in e.g. finite element analysis.
I am relying on the Julia parser to do an initial analysis of the syntax. The equations entered are valid Julia syntax, but will trigger errors on execution because some of the symbols or methods are not available at the point of the problem definition.
So what I do is roughly this:
I have a type that can hold my problem description:
type Cmd f; a; b; end
I have defined a macro so that I have access to the problem description AST. I travers this expression and create a Cmd object from its elements (this is not completely unlike the strategy behind the #mat macro in MATLAB.jl):
macro m(xp)
c = Cmd(xp.args[1], xp.args[3], xp.args[2])
:($c)
end
At a later step, I run the Cmd. Evaluation of the symbols happens only at this stage (yes, I need to be careful of the evaluation context):
function run(c::Cmd)
xp = Expr(:call, c.f, c.a, c.b)
eval(xp)
end
Usage example:
c = #m a^b
...
a, b = 2, 3
run(c)
which returns 9. So in short, the question is relevant in at least some meta-programming scenarios. In my case I have to admit I couldn't care less about performance as all of this is mere preprocessing and syntactic sugar.
In python 3.5, is it possible to predict when we will get an interned string or when we will get a copy? After reading a few Stack Overflow answers on this issue I've found this one the most helpful but still not comprehensive. Than I looked at Python docs, but the interning is not guaranteed by default
Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.
So, my question is about inner intern() conditions, i.e. decision-making (whether to intern string literal or not): why the same piece of code works on one system and not on another one and what rules did author of the answer on mentioned topic mean when saying
the rules for when this happens are quite convoluted
You think there are rules?
The only rule for interning is that the return value of intern is interned. Everything else is up to the whims of whoever decided some piece of code should or shouldn't do interning. For example, "left" gets interned by PyCodeNew:
/* Intern selected string constants */
for (i = PyTuple_GET_SIZE(consts); --i >= 0; ) {
PyObject *v = PyTuple_GetItem(consts, i);
if (!all_name_chars(v))
continue;
PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i));
}
The "rule" here is that a string object in the co_consts of a Python code object gets interned if it consists purely of ASCII characters that are legal in a Python identifier. "left" gets interned, but "as,df" wouldn't be, and "1234" would be interned even though an identifier can't start with a digit. While identifiers can contain non-ASCII characters, such characters are still rejected by this check. Actual identifiers don't ever pass through this code; they get unconditionally interned a few lines up, ASCII or not. This code is subject to change, and there's plenty of other code that does interning or interning-like things.
Asking us for the "rules" for string interning is like asking a meteorologist what the rules are for whether it rains on your wedding. We can tell you quite a lot about how it works, but it won't be much use to you, and you'll always get surprises.
From what I understood from the post you linked:
When you use if a == b, you are checking if the value of a is the value of b, whereas when you use if a is b, you are checking if a and b are the same object (or share the same spot in the memory).
Now python interns the constant strings (defined by "blabla").
So:
>>> a = "abcdef"
>>> a is "abcdef"
True
But when you do:
>>> a = "".join([chr(i) for i in range(ord('a'), ord('g'))])
>>> a
'abcdef'
>>> a is "abcdef"
False
In the C programming language, using a string with "" will make it a const char *. I think this is what is happening here.
This question already has answers here:
Determine variable names dynamically according to a string in Fortran
(4 answers)
Closed 5 years ago.
I'd like to access a real variable with a name equal to a string of characters that I have. Something like this (I'll make the example as clean as possible):
character(len=5) :: some_string
real :: value
value = 100.0
some_string = 'value'
At this point, how do I create an association between the character array value and the name of my real variable, value, so that I can write the value of 100.0 by referring to the string some_string?
That's pretty much not going to happen in Fortran. There are no "dynamic" language features like this available in the language. Variable names are a compile-time only thing, and simply don't exist at runtime (the names have been translated to machine addresses by the compiler).
This is how I work around this:
character(100) :: s
integer :: val
val = 100
write(s,*) val
print *,trim(s)
This prints 100 to the screen. There is some strangeness which I do not understand however, the character s needs to be very large (100 int his case). For instance, if you use 3 instead of 100, it does not work. This is not a critical thing, as the use of trim fixes this, but it would be nice if somebody could answer why this is the case.
Either way, this should work.
I want to implement a check function that given two strings s1 and s2 will check if s2 is the caesar cipher of s1 or not. the inter face needs to be looked like string->string->bool.
the problem is that I am not allowed to use any string functions other than String.length, so how can I solve it? i am not permitted any list array, iterations. Only recursions and pattern matching.
Please help me. And also can you tell me how I can write a substring function in ocaml other than the module function with the above restrictions?
My guess is that you are probably allowed to use s.[i] to get the ith character of string s. This is the same as String.get, but the instructor may not think of it in those terms. Without some form of getting the individual characters for the string, I believe that this is impossible. You should probably double check with your instructor to be sure, but I would be surprised if he had meant for you to be unable to separate a string into characters (which is something that you cannot do with pattern-matching alone in Ocaml).
Once you can get individual characters, the way to do it should be pretty clear (you do not need substring to traverse each string recursively).
If you still want to write substring, creating it would be complex since you don't have access to String.create or other similar functions. But you can write your own version of String.create using recursion, one character string literals (like "x"), the ability to set a character in a string to another (like s.[0] <- c), and string concatenation (s1 ^ s2). Again, of course, all of this is assuming that those operators are allowed to be used.