确定传入列表是否遵循A B模式的函数 [英] A function which will determine that if a passed in list follows an A B pattern

查看:58
本文介绍了确定传入列表是否遵循A B模式的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(define fun4

 (lambda ( ls)

(cond ((null? ls ) #f)

 (cons (((eqv? 'a (car ls))) && ((eqv? 'b (cdr ls)))))

(else (pattern2 cdr ls)))))

在此显示错误-过程应用程序:预期过程,给定:#t(无参数), 我的代码中的错误是什么.逻辑还可以吗???

In this it showing error - procedure application: expected procedure, given: #t (no arguments), What is the erroe in my code. Is logic is fine ???

推荐答案

解决方案中有很多很多错误.让我们看看每种情况下有什么问题:

There are many, many errors in your solution. Let's see what's wrong in each of the conditions:

  1. 递归(空列表)的基本情况是错误的:空列表是递归的退出,这意味着该列表已正确遍历并且遵循模式
  2. 缺少另一个基本情况:如果列表中只有一个元素怎么办?
  3. 如果该模式不成立,则必须立即返回#f,并注意我们如何使用cadr来访问第二个元素,因为&&在Scheme中不起作用,因此必须使用and用于逻辑操作.另外,您在每个测试中都有不必要的,错误的括号(顺便说一句:那些是导致预期过程"错误的括号)
  4. 仅当以上条件均不满足时,我们才进行递归,并通过使用cddr两个元素进一步移到列表中.另外,您必须调用fun4进行递归,而不是pattern2
  1. The base case of the recursion (empty list) is wrong: an empty list is the exit of the recursion, and it means that the list was traversed correctly and it follows the pattern
  2. Another base case is missing: what if the list has a single element?
  3. If the pattern doesn't hold, we must return #f immediately, and notice how we use cadr for accessing the second element, because && doesn't work in Scheme, you must use and for the logical and operation. Also you have unnecessary, erroneous parentheses surrounding each test (by the way: those were the ones causing the "expected procedure" error)
  4. Only if none of the above conditions hold we advance the recursion, and we do so by moving two elements further down the list using cddr. Also you must call fun4 to advance the recursion, not pattern2

这是解决问题的正确方法,请注意如何解决上述问题:

This is the correct way to solve the problem, notice how the above issues were addressed:

(define fun4
  (lambda (ls)
    (cond ((null? ls) #t)                                       ; 1
          ((null? (cdr ls)) #f)                                 ; 2
          ((not (and (eq? 'a (car ls)) (eq? 'b (cadr ls)))) #f) ; 3
          (else (fun4 (cddr ls))))))                            ; 4

始终测试您的过程,以上内容将正常运行:

Always test your procedures, the above will work correctly:

(fun4 '())
=> #t
(fun4 '(a))
=> #f
(fun4 '(a b))
=> #t
(fun4 '(a b a))
=> #f
(fun4 '(a b a b))
=> #t

最后一点,如果不希望空列表遵循该模式,则在调用fun4之前检查它,如果初始输入列表为空,则返回#f.

As a final note, if the empty list is not supposed to follow the pattern, then check for it before calling fun4 and return #f if the initial input list is empty.

这篇关于确定传入列表是否遵循A B模式的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆