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

ⅰ亾dé卋堺 提交于 2019-12-12 06:13:34

问题


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:


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.




回答2:


Maybe adding the precedence of the operators at the top:

%left "+" "-";
%left "*" "/";


来源:https://stackoverflow.com/questions/5013028/how-can-i-parse-character-in-a-file-in-squeak4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!