0

friend, suppose I have a file test.txt, the content of file is "1+2*3", if the fomular directly expressed in Squeak's Workspace, print it will result 9, What I want to get is 7 then I read the file content 1+2*3 from a file. code like this and it works well

ReadFrom
"read the equation from  ./formular.txt"

| fileContents |
fileContents := FileStream 
               readOnlyFileNamed: 'test.txt' 
               do: [:f | f contents ].
^fileContents.

but how can I store the 5 caracters of string "1+2*3" into a collection , further I can use binary tree to calculate the equation? Do somebody can give me some hints? thanks first :)

gal007
  • 6,911
  • 8
  • 47
  • 70
parsifal
  • 879
  • 4
  • 12
  • 21
  • You get 9 because you're sending messages: 1 + 2 * 3 means (1 + 2) * 3. (So if you like, message sending, including arithmetic operators, is always left-associative.) – Frank Shearar Feb 17 '11 at 07:04

2 Answers2

2

The SmaCC tutorial ends up building pretty much what you want.

Quote from said tutorial:

The two lines that we added to the top of the grammar mean that "+" and "-" are evaluated left-to-right and have the same precedence, which is lower than "*" and "/".

SmaCC is a full-blown parser generator for Smalltalk which may be overkill depending on your needs.

If you just want to build a simple calculator you can use the Shunting-yard algorithm to convert an infix mathematical expression into RPN and evaluate it easily.

Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
0

Maybe adding the precedence of the operators at the top:

%left "+" "-";
%left "*" "/";
gal007
  • 6,911
  • 8
  • 47
  • 70