Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace ForthSharp
- {
- public class Forth
- {
- List<string> inputed = new List<string>();
- Dictionary<string,Func<bool>> runDict = new Dictionary<string, Func<bool>>();
- Stack<int> data = new Stack<int>();
- public Forth ()
- {
- }
- private bool runAdd ()
- {
- int a = data.Pop();
- int b = data.Pop();
- data.Push(a+b);
- return true;
- }
- private bool runDot ()
- {
- int a = data.Pop();
- Console.Write(a);
- return true;
- }
- public void init ()
- {
- runDict.Add("+",runAdd);
- runDict.Add(".",runDot);
- }
- public void run ()
- {
- while (true) {
- string word = GetWord().ToLower();
- int wordVal = 0;
- if (word == "bye") //user wants to exit
- {
- break;
- } else {
- if ( runDict.ContainsKey(word)) //word is in the runtime dictonary
- {
- Func<bool> t = runDict[word];
- t.Invoke();
- } else if (int.TryParse(word, out wordVal)){ //word was an interger push it onto stack
- data.Push(wordVal);
- } else {
- }
- }
- }
- }
- private string GetWord (string prompt = "\n> ")
- {
- if (inputed.Count == 0) {
- Console.Write(prompt);
- string input = Console.ReadLine();
- string[] words = input.Split(' ');
- foreach (string a in words)
- {
- inputed.Add(a);
- }
- //return first word
- if (inputed.Count>0)
- {
- string b = inputed[0];
- inputed.Remove(b);
- return b;
- }
- } else { //words are in inputed
- string b = inputed[0];
- inputed.Remove(b);
- return b;
- }
- return "";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement