如何在 Squeak4.1 中解析文件中的字符?
朋友,假设我有一个文件test.txt,文件内容是“1+2*3”,如果直接在Squeak的工作区中表达公式,打印出来会结果9
,我想要什么得到的是7
然后我从文件中读取文件内容1+2*3
。像这样的代码,效果很好,
ReadFrom
"read the equation from ./formular.txt"
| fileContents |
fileContents := FileStream
readOnlyFileNamed: 'test.txt'
do: [:f | f contents ].
^fileContents.
但是如何将字符串“1+2*3”的5个字符存储到集合中,进一步我可以使用二叉树来计算方程?有人可以给我一些提示吗?首先谢谢:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SmaCC 教程最终构建了几乎您想要的内容。
引用上述教程:
SmaCC 是一个成熟的 Smalltalk 解析器生成器,根据您的需要,它可能有点过头了。
如果您只想构建一个简单的计算器,您可以使用 Shunting-yard 算法 进行转换将数学表达式中缀到 RPN 中并轻松对其求值。
The SmaCC tutorial ends up building pretty much what you want.
Quote from said tutorial:
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.
也许在顶部添加运算符的优先级:
Maybe adding the precedence of the operators at the top: