Advertisement
Guest User

Forth

a guest
Apr 5th, 2014
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ForthSharp
  4. {
  5.     public class Forth
  6.     {
  7.         List<string> inputed = new List<string>();
  8.         Dictionary<string,Func<bool>> runDict = new Dictionary<string, Func<bool>>();
  9.         Stack<int> data = new Stack<int>();
  10.         public Forth ()
  11.         {
  12.         }
  13.         private bool runAdd ()
  14.         {
  15.             int a = data.Pop();
  16.             int b = data.Pop();
  17.             data.Push(a+b);
  18.             return true;
  19.         }
  20.         private bool runDot ()
  21.         {
  22.             int a = data.Pop();
  23.             Console.Write(a);
  24.             return true;
  25.         }
  26.         public void init ()
  27.         {
  28.             runDict.Add("+",runAdd);
  29.             runDict.Add(".",runDot);
  30.         }
  31.         public void run ()
  32.         {
  33.             while (true) {
  34.                 string word = GetWord().ToLower();
  35.                 int wordVal = 0;
  36.                 if (word == "bye") //user wants to exit
  37.                 {
  38.                     break;
  39.                 } else {
  40.                     if ( runDict.ContainsKey(word)) //word is in the runtime dictonary
  41.                     {
  42.                         Func<bool> t = runDict[word];
  43.                         t.Invoke();
  44.                     } else if (int.TryParse(word, out wordVal)){ //word was an interger push it onto stack
  45.                         data.Push(wordVal);
  46.  
  47.                     } else {
  48.                     }
  49.                 }
  50.             }
  51.         }
  52.         private string GetWord (string prompt = "\n> ")
  53.         {
  54.             if (inputed.Count == 0) {
  55.                 Console.Write(prompt);
  56.                 string input = Console.ReadLine();
  57.                 string[] words = input.Split(' ');
  58.                 foreach (string a in words)
  59.                 {
  60.                     inputed.Add(a);
  61.                 }
  62.                 //return first word
  63.                 if (inputed.Count>0)
  64.                 {
  65.                     string b = inputed[0];
  66.                     inputed.Remove(b);
  67.                     return b;
  68.                 }
  69.             } else { //words are in inputed
  70.                 string b = inputed[0];
  71.                 inputed.Remove(b);
  72.                 return b;
  73.             }
  74.             return "";
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement