简体   繁体   English

球拍中的语法错误是否相等?

[英]Syntax Error in Racket equal?

I am trying pass in a list input to conversation and have the function check to see if the first element in another list (keyword) matches to the first element of the list that user passed in. If the two match then output a zero otherwise pass the tail of the inputted list recursively back to itself. 我正在尝试将列表输入传递给会话,并让函数检查是否另一个列表(关键字)中的第一个元素与用户传递的列表中的第一个元素匹配。如果两个匹配,则输出零,否则通过输入列表的尾部递归返回自身。

(define keyword '(am I))

(define (conversation input)
     (cond
      ((equal? (car keyword) (car input)) 0)
      (else (conversation (cdr input)))))

The error I get is: 我得到的错误是:

car: contract violation
expected: pair?
given: '()

I understand that equal? 我明白相等吗? compares two elements, a pair, but what I do not understand is why it would create an error when the car of both lists are both exactly an element. 比较两个元素,一对,但是我不明白的是为什么当两个列表的汽车都恰好是一个元素时,为什么会产生错误。 Any help would be much appreciated, I'm assuming the solution is rather simple but I can't seem to see it. 任何帮助将不胜感激,我假设解决方案非常简单,但我似乎看不到它。

My goal is create several functions that pattern match and output appropriate dialog but without the use of regular expressions or other libraries. 我的目标是创建一些模式匹配并输出适当对话框的函数,但不使用正则表达式或其他库。 There is no mandate not to use the two mentioned above but I would like to do it without them to get a better understanding of the logic and the code. 没有授权不要使用上面提到的两个,但是我想在没有它们的情况下这样做,以更好地理解逻辑和代码。 Thanks for the help! 谢谢您的帮助!

The first thing to consider is that you have no condition of failure. 首先要考虑的是您没有失败的条件。 You assume there's either a match now with the car , or there will be a match later with the cdr . 您假设现在car匹配,或者稍后与cdr匹配。 But there may be no match at all, and you will cdr down your list until your list is '() . 但也有可能不匹配的一切,你会cdr ,直到你的清单跌列表'() As there is no such thing as the car of '() you are getting an error when you try to extract it. 由于不存在'()car ,因此尝试提取时会出现错误。 Therefore the first thing to do is make sure you've handled this case. 因此,要做的第一件事就是确保您已经处理了这种情况。 I don't know what you intend to do in this case, so I have made the procedure return #f . 在这种情况下,我不知道您打算做什么,因此我使过程返回了#f

Next you consider what to do if the symbols do match. 接下来,您要考虑如果符号确实匹配该怎么办。 In your case you are choosing to return 0 . 在您的情况下,您选择返回0 This part seems to have no problems. 这部分似乎没有问题。

Finally, we consider what to do if the car s do not match. 最后,我们考虑如果car不匹配该怎么办。 In this case we continue searching the input. 在这种情况下,我们将继续搜索输入。 This part seems to have no problems. 这部分似乎没有问题。

(define (conversation input)
  (cond ((null? input) #f)
        ((eq? (car input) (car keyword))
         0)
        (else
         (conversation (cdr input)))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM