How can I parse character in a File in Squeak4.1?

2019-09-04 09:11发布

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 :)

1条回答
Ridiculous、
2楼-- · 2019-09-04 09:16

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.

查看更多
登录 后发表回答