Guest User

Untitled

a guest
Jan 5th, 2015
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import os
  2. from strutils import parseFloat
  3. import sequtils
  4. import tables
  5. import strutils
  6.  
  7. type FormulaKind = enum
  8. fkLit,
  9. fkVar,
  10. fkRef,
  11. fkMul
  12.  
  13. type Formula = ref object
  14. case kind: FormulaKind
  15. of fkLit:
  16. value: float
  17. of fkVar:
  18. name: string,
  19. value: Formula
  20. of fkRef:
  21. name: string
  22. of fkMul:
  23. terms: array[0..1, Formula]
  24.  
  25. proc pat2kind(pattern: string): FormulaKind =
  26. case pattern[0]
  27. of '*': fkMul
  28. of '0'..'9': fkLit
  29. of 'a'..'z' : fkRef
  30. of '=': fkVar
  31. else: fkLit
  32.  
  33. proc buildTokens(line: string) : seq[Formula] =
  34. result = @[]
  35. for c in line.split(" "):
  36. var kind = pat2kind c;
  37. case kind
  38. of fkLit: result.add Formula(kind:kind, value: parseFloat(c))
  39. of fkMul: result.add Formula(kind:kind)
  40. of fkRef: result.add Formula(kind:kind, name:c)
  41. of fkVar: result.add Formula(kind:kind, name:c) #refactor
  42.  
  43. proc buildFormula( s: var seq[Formula] ): Formula =
  44. if len(s) > 0:
  45. var c:Formula = s[0]
  46. s.delete(0, 0)
  47. case c.kind
  48. of fkLit:
  49. result = c
  50. of fkVar:
  51. result = c
  52. result.name = buildFormula(s).name # get ref token name
  53. result.value = buildFormula s # get value
  54. of fkRef:
  55. result = c
  56. of fkMul:
  57. result = c
  58. result.terms[0] = buildFormula s
  59. result.terms[1] = buildFormula s
  60.  
  61. # Print out the Formula for debugging, best use after buildFormula
  62. proc print(token:Formula):string =
  63. case token.kind
  64. of fkLit: $token.value
  65. of fkMul: "Mult of (" & print(token.terms[0]) & " " & print(token.terms[1]) & ")"
  66. of fkVar: "Var " & token.name & " = " & print(token.value)
  67. of fkRef: "Ref " & token.name
  68.  
  69. # Crunch the calcuations
  70. proc compute(token:Formula, table:TTable[string, Formula]):float =
  71. case token.kind
  72. of fkLit: token.value
  73. of fkMul: compute(token.terms[0]) * compute(token.terms[1])
  74. of fkRef: table[token.name]
  75. of fkVar:
  76. table[token.name] = token.value
  77. compute(token.value)
  78.  
  79. # Main Program
  80. var i = open("calcadd.txt");
  81. var line : char;
  82. var table = initTable[string, Formula]()
  83. for line in i.lines:
  84. var tokens:seq[Formula] = buildTokens(line)
  85. var f:Formula = buildFormula(tokens)
  86. echo compute(f, table)
Advertisement
Add Comment
Please, Sign In to add comment