PLT 方案菜鸟:布尔值和/或不是过程?
我正在尝试为数字电子课程制作一个真值表生成器,因为这就是我在业余时间享受乐趣的方式,并且不要评判我。
无论如何,我想我应该有一个哈希,其中相当于运算符的字符串作为键,以及与这些运算符相对应的方案过程作为值。
例如,
(define operator-table #hash(("+" . or) ("*" . and)))
所以我可以做类似的事情
(lambda (a b) ((hash-ref operator-table (string-ref input-str i)) a b))
现在我意识到上面的方法可能无法正常工作,但事实上我什至无法修改它,直到我得到正确的结果,因为显然 and
和 或
在Scheme中是特殊的。在 REPL 中,如果我输入 not
,它会回复 #
。但是,如果我给它 and
或 or
,它会显示 and: bad syntax in: and
。是否有我可以使用的 and
程序版本?或者我必须用 lambda 制作一个吗?或者我完全错过了一些东西?
我不从一开始就使用 lambda 的唯一原因是我不想失去内置 和
的可变数量能力 [我可以做 (and #t #f)
以及(和#t #f #f #t #f #t)
]。
I'm trying to make a truth-table generator for a digital electronics course because that's how I have fun in my spare time and don't judge me.
Anywho, I figured I'd have a hash with the string equivalent of operators as keys, and the Scheme procedures that correspond to those operators as values.
E.g.
(define operator-table #hash(("+" . or) ("*" . and)))
So I could do something like
(lambda (a b) ((hash-ref operator-table (string-ref input-str i)) a b))
Now I realize the above probably won't work right, but as it is I can't even tinker with it until I get it right, because apparently and
and or
are special in Scheme. At the REPL, if I type in not
it replies #<procedure:not>
. But if I give it and
or or
, it says and: bad syntax in: and
. Is there a procedure version of and
I can use? Or do I have to make one with lambda
? Or am I missing something entirely?
The only reason I didn't just go with lambda from the get-go is that I don't want to lose the variable-arity abilities of the builtin and
[I can do (and #t #f)
as well as (and #t #f #f #t #f #t)
].
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想使用
and
和or
的函数形式(限制它们不会短路)并且不丢失变量的arity属性,那么你可以轻松地这样做:(values
是 (PLT) 方案中惯用的恒等函数。)If you want to use a function form of
and
andor
(with the limitation that they will not short-circuit) and not lose the variable arity property, then you can easily do so:(
values
is the idiomatic identity function in (PLT) Scheme.)是的,它们不能是过程,因为Scheme(像大多数语言一样)是一种“热切”语言——过程的每个参数在过程控制(接收参数值)之前都会被评估。
and
和or
需要“短路”——一旦知道最终结果就停止参数评估——所以它们不能是常规过程/函数任何急切的语言(“惰性”语言,例如 Haskell——其中每个参数仅在需要时才被评估——是一个非常不同的品种,并且不需要这个“常规函数” “与“特殊形式”的区别......但是,可惜,Scheme 并不是其中之一!)。Yep, they can't be procedures because Scheme (like most languages) is an "eager" language -- every argument to a procedure gets evaluated before the procedure takes control (receiving the argument values).
and
andor
need to "short-circuit" -- stop argument evaluation as soon as the final result is known -- so they can't be regular procedures/functions in any eager language ("lazy" languages, such as Haskell -- where each argument is evaluated only if, when and as needed -- are a very different breed, and don't need this "regular function" versus "special form" distinction... but, alas, Scheme just isn't one of those!).