Good parsing approach after tokenization [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I wrote a program in which I read a string or file and tokenize it.
Example String :
"int w = sad&&s||a|d++ != == < > >= <= -- sadsa++ % int sads = 232.32; if reg string test = \"Hello World\";% % +- + - / * ** false true"
Exmaple Output:
Token[Type:'Identifier',Value:'int',Line:'1',Position:'3']
Token[Type:'Literal',Value:'w',Line:'1',Position:'4']
Token[Type:'Assign',Value:'=',Line:'1',Position:'4']
Token[Type:'Literal',Value:'sad',Line:'1',Position:'8']
Token[Type:'Logical',Value:'&&',Line:'1',Position:'8']
Token[Type:'Literal',Value:'s',Line:'1',Position:'11']
Token[Type:'Logical',Value:'||',Line:'1',Position:'11']
Token[Type:'Literal',Value:'a',Line:'1',Position:'14']
Token[Type:'Unknown',Value:'|d',Line:'1',Position:'14']
Token[Type:'Literal',Value:'d',Line:'1',Position:'16']
Token[Type:'Arithmetic',Value:'++',Line:'1',Position:'16']
Token[Type:'Relational',Value:'!=',Line:'1',Position:'18']
Token[Type:'Relational',Value:'==',Line:'1',Position:'20']
Token[Type:'Relational',Value:'<',Line:'1',Position:'22']
Token[Type:'Relational',Value:'>',Line:'1',Position:'23']
Token[Type:'Relational',Value:'>=',Line:'1',Position:'24']
Token[Type:'Relational',Value:'<=',Line:'1',Position:'26']
Token[Type:'Arithmetic',Value:'--',Line:'1',Position:'28']
Token[Type:'Literal',Value:'sadsa',Line:'1',Position:'35']
Token[Type:'Arithmetic',Value:'++',Line:'1',Position:'35']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'37']
Token[Type:'Identifier',Value:'int',Line:'1',Position:'41']
Token[Type:'Literal',Value:'sads',Line:'1',Position:'45']
Token[Type:'Assign',Value:'=',Line:'1',Position:'45']
Token[Type:'DoubleValue',Value:'232.32',Line:'1',Position:'51']
Token[Type:'Semicolon',Value:';',Line:'1',Position:'51']
Token[Type:'Identifier',Value:'if',Line:'1',Position:'53']
Token[Type:'Literal',Value:'reg',Line:'1',Position:'56']
Token[Type:'Identifier',Value:'string',Line:'1',Position:'62']
Token[Type:'Literal',Value:'test',Line:'1',Position:'66']
Token[Type:'Assign',Value:'=',Line:'1',Position:'66']
Token[Type:'StringValue',Value:'Hello World',Line:'1',Position:'78']
Token[Type:'Semicolon',Value:';',Line:'1',Position:'78']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'78']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'79']
Token[Type:'Unknown',Value:'+-',Line:'1',Position:'80']
Token[Type:'Arithmetic',Value:'+',Line:'1',Position:'82']
Token[Type:'Arithmetic',Value:'-',Line:'1',Position:'83']
Token[Type:'Arithmetic',Value:'/',Line:'1',Position:'84']
Token[Type:'Arithmetic',Value:'*',Line:'1',Position:'85']
Token[Type:'Unknown',Value:'**',Line:'1',Position:'86']
Token[Type:'Identifier',Value:'false',Line:'1',Position:'93']
Token[Type:'Identifier',Value:'true',Line:'1',Position:'97']
Elapsed time: 31
(Ignore Position, has to be fixed in the future)
So now I do not really know a good approach to further interpret this in order to run a simple little scripting language on my own.

A good first approach is to come up with names for each thing, like "operation", "operand", "literal", "declaration" etc.
Then make a function that can read each of those from your token stream, and calls the others where appropriate. E.g. If you have:
operation: <operand> <operator> <operand>
operator: + | -
operand: <number> | <string>
etc., then you can have a function (pseudocode):
Operation parseOperation( tokens )
{
Operand operand1 = parseOperand( tokens )
Operation theOp = new Operation( tokens.fetchNextToken() )
Operand operand2 = parseOperand( tokens )
theOp.operand[0] = operand1
theOp.operand[1] = operand2
return theOp
}
and implement the other functions in a similar way. Of course, some functions may have to examine the next token to decide which other function to call, or even look ahead several tokens.
This is usually called a "recursive descent" parser.
Each of the functions returns an object that represents an operation and has its arguments hanging off of it. This is basically a tree structure, which you can then recursively walk ("depth-first").
The easiest way is to give the different object types you define dor your operations and values methods like asString() or asInt() and then do things like:
int Operation::asInt()
{
int a = operand[0].asInt()
int b = operand[1].asInt()
return a + b;
}
Objects that are already the right type (like an IntOperand class) would just return their value:
int IntOperand::asInt()
{
return self.numericValue
}
or whatever. Objects that aren't the right type either produce an error instead of returning a value, or convert themselves. So no matter how complex the expression, in the end you get an int or string or whatever out.
To run a program, you can now ask the bottom-most object for its value.

Related

multiplication in C# basic program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In the Main function, declare three integer variables (name them arbitrarily) and initialize these variables with values (ideally different). Write a program that computes the following arithmetic expression: Multiply the values of the last two variables and subtract the value of the first variable from the obtained result. Write the arithmetic expression and its result on the screen in a suitable way.
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int prvni = 10;
int druha = 20;
int treti = 30;
int vysledek = (treti * druha) - prvni;
Console.WriteLine("Výsledek: {vysledek}");
}
}
}
String-interpolation in that way requires a $ (dollar-sign) before the string to specify that you are doing interpolation, so: Console.WriteLine($"Výsledek: {vysledek}");
For more examples on string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
An alternative solution could be to simply concatenate the variable to the string: Console.WriteLine("Výsledek: " + vysledek);
You need to print the varable correctly.
Console.WriteLine("the answer {0}", vysledek);
Take care,
Ori

Parameters in parentheses after a method name: what are they and what do they do? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Newb to C# and OOP. My journey thus far has been to take code bases that I've inherited from former developers and either address issues, or add enhancements, whilst trying to understand said code bases' structures from front-to-back.
I'm having trouble fully grasping the concept around the parameters which follow the initial declaration of a method. Here's an example of a method I'm working with:
public List<Entity> ParseCsvFile(List<string> entries, string urlFile)
{
entries.RemoveAt(entries.Count - 1);
entries.RemoveAt(0);
List<Entity> entities = new List<Entity>();
foreach (string line in entries)
{
Entity entityManagement = new Entity();
string[] lineParts = line.Split('|');
entityManagement.Identifier = lineParts[0];
entityManagement.ProductId = 1234;
entityManagement.Category = "ABCDE";
entities.Add(entityManagement);
}
return entities;
}
The part after ParseCsvFile in parentheses: (List<string> entries, string urlFile)
Could someone explain what these are and what they do, perhaps with metaphors/analogies/real-world examples?
It might be easier to see their purpose if you look at a simpler function for example:
public int Add(int number1, int number2)
{
return number1 + number 2;
}
Above there is a function that adds two numbers together and returns the result. It is a set of instructions to follow. How can it follow the instructions if it doesn't know what numbers to use.
That's where calling the function comes in.
for example:
var result = Add(2, 5);
In this scenario result = 7.
2 is replacing number1 in the function and 5 is replacing number2.

Initialize int variable to minus one in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've come across some code where the variables are initialized to minus one. That's in some old code, is there any reason behind that? Because as far as I know all value types are initialized to zero.
I've tested the code and it doesn't change anything to leave the int variable uninitialized or with minus one, the result is the same.
Would you enlighten me?
class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int Number = -1; //or -> int Number;
int returnedValue = del(out Number);
Console.WriteLine("returnedValue = {0}", returnedValue);
Console.ReadLine();
}
public static int SampleMethodOne(out int Number)
{
return Number = 1;
}
public static int SampleMethodTwo(out int Number)
{
return Number = 3;
}
}
public delegate int SampleDelegate(out int Number);
/returns 2
TL;DR: it depends, maybe there is no answer
Possible answer:
Initializing variable is better. you never know how it can be used in some later functions where having an unexpected value may be dangerous (when the code is optimized, you cannot be sure of the default value if not initialized).
In some case, an int may be used for some compatibility reason in the API when you just need an uint. In such a case, initializing to a negative value may be an easy way to detect an unset/invalid value.
No real reason, just an habit from the developer. I agree with comments, ask him if possible

How can I get the datatype of an array in C#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am making a sort of statistical software that firstly needs to 'detect' the datatype of an array.
Firstly, X[,] is an array of sometype, can be all strings, all double, all ints or a combination of all.
Now, for every column X[] I need to know the datatype. Like:
If everything is 0 or 1, then Boolean (or binomial)
elseIf everything is integer, then integer
elseIf everything is double, then double
else: String
I need something like this in C#.
So it seems what you're trying to do here is find the "lowest common denominator" of types here. The most derived type that all of the items in the collection "are".
We'll start out with this helper method to get the entire type hierarchy of an object (including itself):
public static IEnumerable<Type> BaseClassHierarchy(object obj)
{
Type current = obj.GetType();
do
{
yield return current;
current = current.BaseType;
} while (current != null);
}
Now we can take a sequence of objects, map each to its hierarchy, intersect all of those sequences with each other, and then the first item of that result is the most derived type that is common to all of the other objects:
public static Type MostDerivedCommonType(IEnumerable<object> objects)
{
return objects.Select(o => BaseClassHierarchy(o))
.Aggregate((a,b)=> a.Intersect(b))
.First();
}
One simple idea is you can try to cast/parse as the different types and if that fails, move on to the next type. A very brief example of this is:
foreach (var element in myArray) {
double parsedDouble; int parsedInt;
var defaultValue = element.ToString();
if (Double.TryParse(defaultValue, out parsedDouble)) {
// you have something that can be used as a double (the value is in "parsedDouble")
} else if (Int32.TryParse(defaultValue, out parsedInt)){
// you have something that can be used as an integer (the value is in "parsedInt")
} else {
// you have something that can be used as an string (the value is in "defaultValue")
}
}
I believe that should probably get you started. Good luck!
Note
As other's have said - it is better to use strong types in C#. In most cases you can probably select a single type and use that rather than performing the checks above.

how to concatenate a - in a string c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i am trying to make a calculator in c# and i am looking to concatenate a - into a string or something similar. the expected output should also minus the two variables. EX,
string ready;
private void minus_Click(object sender, EventArgs e)
{
long minusnumber = 32;
ready = minusnumber + "-";
}
.
.
.
private void equals_Click(object sender, EventArgs e)
{
long equalsNumber1 = 32;
ready += equalsNumber1;
MessageBox.Show(ready);
}
and console output would be 0
but it is taking "-" as minus not subtracting the two numbers.
ive tried escaping it (not sure if i did escape it right) and it didn't help:/
use
string.concat(minusnumber , "-");
It might help you. You can use n numbers of object on concat method.
I think this might be what you are hoping to accomplish, but it is a bit unclear. This will take minusnumber and negate it. So then when you add previous number to minusnumber, it will in effect subtract. Only problem with this is your ready variable appears to be a string.
private void minus_Click(object sender, EventArgs e)
{
long minusnumber = 32;
ready = -minusnumber;
}
Perhaps ready should be a long. When you are getting user input, you can use TryParse:
string userText = "54";
long userInput;
Int64.TryParse(userText, out userInput);
ready -= userInput;
From what you've written, the variable ready in minus_Click is local to minus_Click and not the global you probably intended it to be.
Instead of:
string ready = minusnumber + "-";
Perhaps you meant:
ready = minusnumber + "-";
EDIT
Now that the question is patched, it seems that the real question is "Why does MessageBox.Show(ready); show "32-32" instead of 0?" If that is the question, the reason is you are showing the value of the variable ready. This is a string. You started it at "32-" then added "32". The result of this string concatenation is "32-32". In order to perform arithmetic evaluation you need to write the code to parse the string and do the evaluation. Or find someone that has written an Eval() method for strings containing arithmetic expressions.
For make calculator you must use Polish Notation or RPN

Categories