I'm assuming this isn't possible, but I'm just wondering if you could convert an expression to a string.
For example, the following adds five and five together
print(tostring(5 + 5)) --> 10
I was wondering if you could do something along the lines of the following.
print(tostring(5 + 5)) --> 5 + 5
I'm wondering because I'm making a graphing calculator, and to create a function, it has to be a string. I was hoping I could make it more user-friendly by making it so you can just input an expression such as x ^ 2 instead of "x ^ 2"
What you want to do is convert an expression 5 + 5 to a string "5 + 5".
AFAIK, you can't do that in Lua. However, you can do the opposite by transforming "5 + 5" to 5 + 5 using loadstring. Hope it help.
If you have the expression as part of some Lua code, you can parse that code into something like Abstract Syntax Tree (AST) and then convert that AST into whatever structure you need, which may be a string or a function (this may be more convenient for your graphing calculator).
There are several Lua parsers that can do this (both converting Lua code into AST and generating Lua code from AST); both Metalua (5.1 only? bytecode generation only?) and TypedLua (5.2+) can do that and there are some other Lua parsers listed here.
Related
I recently found this code snippets on the Swift 5 Book.
print(#"Write an interpolated string in Swift using \(multiplier)."#)
// Prints "Write an interpolated string in Swift using \(multiplier).”
print(#"6 times 7 is \#(6 * 7)."#)
// Prints "6 times 7 is 42.”
I learnt it was an accepted proposal in Swift 5 for enhancing string literals delimiters to support raw text, with so many examples given.
My question is when and how is it used in practical cases because from the examples given above, I would still clearly achieve what I want to even without the # signs!
To give just one example where it is very useful. How about when writing Regex, previously it was a nightmare as you had to escape all special characters. E.g.
let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
Can now be replaced with
let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
Much easier to write. Now when you find a regex online, you can just copy and paste it in without having to spend ages escaping special characters.
Edit:
Can read here
https://www.hackingwithswift.com/articles/162/how-to-use-raw-strings-in-swift
Trying to understand how "%s%s" %(a,a) is working in below code I have only seen it inside print function thus far.Could anyone please explain how it is working inside int()?
a=input()
b=int("%s%s" %(a,a))
this "%s" format has been borrowed from C printf format, but is much more interesting because it doesn't belong to print statement. Note that it involves just one argument passed to print (or to any function BTW):
print("%s%s" % (a,a))
and not (like C) a variable number of arguments passed to some functions that accept & understand them:
printf("%s%s,a,a);
It's a standalone way of creating a string from a string template & its arguments (which for instance solves the tedious issue of: "I want a logger with formatting capabilities" which can be achieved with great effort in C or C++, using variable arguments + vsprintf or C++11 variadic recursive templates).
Note that this format style is now considered legacy. Now you'd better use format, where the placeholders are wrapped in {}.
One of the direct advantages here is that since the argument is repeated you just have to do:
int("{0}{0}".format(a))
(it references twice the sole argument in position 0)
Both legacy and format syntaxes are detailed with examples on https://pyformat.info/
or since python 3.6 you can use fstrings:
>>> a = 12
>>> int(f"{a}{a}")
1212
% is in a way just syntactic sugar for a function that accepts a string and a *args (a format and the parameters for formatting) and returns a string which is the format string with the embedded parameters. So, you can use it any place that a string is acceptable.
BTW, % is a bit obsolete, and "{}{}".format(a,a) is the more 'modern' approach here, and is more obviously a string method that returns another string.
It should be very easy, but I am looking for an efficient way to perform it.
I know that I could split the string into two parts and insert the new value, but I have tried to substitute each line between the indexes 22-26 as follows:
line.replace(line[22:26],new_value)
The Problem
However, that function substitutes everything in the line that is similar to the pattern in line[22:26].
In the example below, I want to replace the marked number 1 with number 17:
Here are the results. Note the replacement of 1 with 17 in several places:
Thus I don't understand the behavior of replace command. Is there a simple explanation of what I'm doing wrong?
Why I don't want RE
The values between index 22-26 are not unified in form.
Note: I am using python 3.5 on Unix/Linux machines.
str.replace replaces 1 sub-string pattern with another everywhere in the string.
e.g.
'ab cd ab ab'.replace('ab', 'xy')
# produces output 'xy cd xy xy'
similarly,
mystr = 'ab cd ab ab'
mystr.replace(mystr[0:2], 'xy')
# also produces output 'xy cd xy xy'
what you could do instead, to replace just the characters in position 22-26
line = line[0:22] + new_value + line[26:]
Also, looking at your data, it seems to me to be a fixed-width text file. While my suggestion will work, a more robust way to process this data would be to read it & separate the different fields in the record first, before processing the data.
If you have access to the pandas library, it provides a useful function just for reading fixed-width files
I am learning Groovy and am pretty impressed with how it allows one to build a intelligent DSL, but I am a bit confused by the rules for when parentheses and dots are optional. Consider the following code:
Integer take(Integer x) {x}
take 3 plus 4
This works as expected and produces an output of 7 (when ran in the console), as groovy understands that last line as take(3).plus(4).
Now, println take 3 plus 4 does not work as groovy understands that as println(take).3(plus).4 which is nonsense.
Every example that I am seeing shows these sort of expression by themselves on a line, but apparently
s = take 3 plus 4
works and stores the result 7 in s. My question is, why does
println( take 3 plus 4 )
not work? Obviously, groovy will parse these sort of expressions even if they are not by themselves on a line (as shown by the assignment working). I would have thought that adding those parentheses would remove the ambiguity from the form of that line that doesn't work and that it would print out 7 as I intended.
Instead groovy gives an error 'unexpected token: 3'. As far as I can tell, groovy will not allow optional parentheses or dots inside that println, even though it doesn't seem to be ambiguous. When exactly does this sort of trick work?
This falls into the category of a nested method call, and in that case you cannot omit the parentheses. This is causing ambiguity and the results are unexpected, as the println method thinks you are passing it multiple parameters. You could reduce the ambiguity by using a groovy string in the println method.
println "${take 3 plus 4}"
More info: Omit Parentheses
I am trying to write a Forth interpreter in Haskell. There are many sub problems and categories to accomplish this, however, I am trying to accomplish the most basic of steps, and I have been at it for some time in different approaches. The simple input case I am trying to get to is "25 12 +" -> [37]. I am not worried about the lists in Forth are backwards from Haskell, but I do want to try and accommodate the extensibility of the input string down the road, so I am using Maybe, as if there is an error, I will just do Nothing.
I first tried to break the input string into a list of "words" using Prelude's words function. From there I used Prelude's reads function to turn it into a list of tuples (Int,String). So this works great, up until I get to a command "word", such as the char + in the sample problem.
So how do I parse/interpret the string's command to something I can use?
Do I create a new data structure that has all the Forth commands or special characters? (assuming this, how do I convert it from the string format to that data type?)
Need anything else, just ask. I appreciate the help thinking this through.
read is essentially a very simple string parser. Rather than adapting it, you might want to consider learning to use a parser combinator library such as Parsec.
There are a bunch of different tutorials about parser combinators so you'll probably need to do a bit of reading before they 'click.' However, the first example in this tutorial is quite closely related to your problem.
import Text.Parsec
import Text.Parsec.String
play :: String -> Either ParseError Integer
play s = parse pmain "parameter" s
pmain :: Parser Integer
pmain = do
x <- pnum `chainl1` pplus
eof
return x
pnum = read `fmap` many1 digit
pplus = char '+' >> return (+)
It's a simple parser that evaluates arbitrarily long lists:
*Main> play "1+2+3+4+5"
Right 15
It also produces useful parse errors:
*Main> play "1+2+3+4+5~"
Left "parameter" (line 1, column 10):
unexpected '~'
expecting digit, "+" or end of input
If you can understand this simple parser, you should be able to work out how to adapt it to your particular problem (referring to the list of generic combinators in the documentation for Text.Parsec.Combinator). It will take a little longer at first than using read, but using a proper parsing library will make it much easier to achieve the ultimate goal of parsing Forth's whole grammar.