如何在 Squeak4.1 中解析文件中的字符?

发布于 2024-10-18 00:54:34 字数 444 浏览 2 评论 0原文

朋友,假设我有一个文件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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放低过去 2024-10-25 00:54:34

SmaCC 教程最终构建了几乎您想要的内容。

引用上述教程:

我们添加到语法顶部的两行意味着“+”和“-”从左到右计算并且具有相同的优先级,低于“*”和“/”。< /p>

SmaCC 是一个成熟的 Smalltalk 解析器生成器,根据您的需要,它可能有点过头了。

如果您只想构建一个简单的计算器,您可以使用 Shunting-yard 算法 进行转换将数学表达式中缀到 RPN 中并轻松对其求值。

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.

可可 2024-10-25 00:54:34

也许在顶部添加运算符的优先级:

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

Maybe adding the precedence of the operators at the top:

%left "+" "-";
%left "*" "/";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文