<p>Hi guys, i'm making a lexer/parser to interpret natural language.
it's based loosely on Rob Pike's state machine talk. <a href="https://www.youtube.com/watch?v=HxaD_trXwRE" rel="nofollow">https://www.youtube.com/watch?v=HxaD_trXwRE</a>
But my state functions are closures with all the possible state functions that they can return stored in a map.
(non compiling example): <a href="https://play.golang.org/p/1F5mGeSdh_" rel="nofollow">https://play.golang.org/p/1F5mGeSdh_</a>
I chose this way because i wanted a solution that was quick even at scale and a map is very quick for looking up key->val.
I didn't use globals because some-one could write to a global and corrupt data.
But I didn't want to allocate a new map every time I lex input, so i went with closure functions and a init function for every closure. This way the functions are available on the global scope.</p>
<p>So I think it's an elegant solution for the problem, but it doesn't read very easily.
Is there a more readable, or idiomatic way to do the same thing?</p>
<p>Your help is greatly appreciated
Cheers, Mario</p>
<hr/>**评论:**<br/><br/>Fwippy: <pre><p>You can just use a "global" map. Really, it's package-level, as it lives under <code>yourpkg.keyWords</code>.</p>
<p>And if you don't Uppercase the first letter, it won't be exported / visible to anyone who uses your library, so the only person who can read/write to it is you.</p></pre>itsamemmario: <pre><p>Hey man, thanks for the input. It might come out a lot cleaner that way. The reason i chose to put it in closures is because my code would have to be worked on with a team afterwards(i hope). It's just the basic setup. I'm trying to make it hard to use the package wrongly by designing the code in a way that the "global" variables can't be accessed on the global scope. and don't have to be re-allocated. Also every stateFn holds a slightly different map, since certain keywords need different state functions in different contexts. And the ability to be able to pass the wrong map to a stateFn seems dangerous.</p>
<p>Although i've never used this approach before, it might lead to messy code down the road. But my hope is less messy code than straight-up globals.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传