【问题标题】:Scheme - Correct use of "and" in an if-sentence方案 - 在 if 句中正确使用“and”
【发布时间】:2014-10-15 21:39:35
【问题描述】:

我目前正在用 Scheme 编写一个小项目来完成一项任务。好久没用Scheme了,语法不强。

问题是在 if 句中使用“and”。我在日历中有一个约会列表,但我只想要那些在某个时间间隔之间的约会。因此,我需要检查开始和结束时间。

我想要实现的在 C# 中看起来像这样:

List<appointment> appointments = new List<appointment>();

    foreach (appointment app in calendar) {
        if(app.getstart() >= from-time && app.getend() <= to-time) {
            appoinments.add(app);
        }
    }

我目前在 Scheme 中的内容是这样的:

(define (time-calendar cal from-time to-time)
  (map (lambda (app)(if (> from-time (send 'getstart app)) #t #f))
         (send 'getappointments cal)))

获取日历“cal”和时间间隔(从时间到时间) 然后我从 cal 获取约会(应用程序)并对其进行迭代。对于他们每个人,我检查从时间是否大于“应用程序”的开始时间。相应地返回真或假。这很好用,但我仍然需要考虑约会是否也在“到时间”之前结束。这应该是添加另一个条件的简单问题,但我根本无法让它工作。

谁能帮助我检查第二个变量的正确语法? 我知道Racket documentation,但我仍然无法解决我的问题。

我尝试将 if 语句更改为 cond。

我也尝试了一堆“和”部分的变体,类似于这个,但无法正确语法:

(define (time-calendar cal from-time to-time)
  (map (lambda (app)(if (and((> from-time (send 'getstart app))) (< to-time (send 'getend app))) #t #f))
         (send 'getappointments cal)))

【问题讨论】:

    标签: if-statement scheme conditional-statements racket


    【解决方案1】:
    (and expression1 expression2 ...)
    

    过多的括号被理解为好像你的表达式要像一个过程一样应用。例如。

    (and ((if some-var + -) 4 6))
    

    这里的结果是 -2 或 10,具体取决于 some-var 的值。 and 是多余的,因为 (and x)x 相同。

    至于你的代码,应该是这样的:

    (define (time-calendar cal from-time to-time)
      (map (lambda (app)
             (and (> from-time (send 'getstart app)) 
                  (< to-time (send 'getend app))))
           (send 'getappointments cal)))
    

    if 是多余的,因为如果其中一个为假,and 的计算结果为 #f&gt;&lt; 始终计算为 #f#t。即使不是这样,您也可以使用除#f 之外的所有数据,因此在大多数情况下,额外的if 是多余的。如果您需要其他表达式返回的内容,则使用 if 和整个表达式是谓词。 现在因为&gt; 接受了很多你实际上不需要and 的参数:

    (define (time-calendar cal from-time to-time)
      (map (lambda (app)
             (> from-time (send 'getstart app) to-time))
           (send 'getappointments cal)))
    

    【讨论】:

    • 我永远不会认为我可以完全跳过“如果”。感谢您的详细解释,我完全理解您的回答!
    • 我的下一次阅读可能必须评估真假 - 无论我如何选择从时间、到时间和存储在约会中的时间,一切都评估为假。好吧,至少我走得更远了。 :)
    • @Treelink 我没有校对你的逻辑。看来您可能需要将&gt;&lt; 切换。 (&gt; from-time (send 'getstart app) to-time) 表示 (send 'getstart app) 需要小于 from-time 并且大于 to-time。例如(&gt; 5 3 1) ; ==&gt; #t,因为5 &gt; 3 &gt; 1。你看到了吗?
    • 你又说对了!我在其他地方也搞砸了,但 > 也应该是
    猜你喜欢
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多