问题
(define fun4
(lambda ( ls)
(cond ((null? ls ) #f)
(cons (((eqv? 'a (car ls))) && ((eqv? 'b (cdr ls)))))
(else (pattern2 cdr ls)))))
In this it showing error - procedure application: expected procedure, given: #t (no arguments), What is the erroe in my code. Is logic is fine ???
回答1:
There are many, many errors in your solution. Let's see what's wrong in each of the conditions:
- 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
- Another base case is missing: what if the list has a single element?
- If the pattern doesn't hold, we must return
#fimmediately, and notice how we usecadrfor accessing the second element, because&&doesn't work in Scheme, you must useandfor 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) - 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 callfun4to advance the recursion, notpattern2
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
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.
回答2:
(define fun
(lambda (ls)
(cond ((null? ls) #t)
((and (eq? (car ls) 'a) ; the first item is a
(list? (cdr ls)) ; the rest of the list
(not (null? (cdr ls))) ; which is not null
(eq? (cadr ls) 'b) ; and it starts with b
(fun (cddr ls))) #t) ; and the rest of the expression is
(else #f)))) ; also in the A B format
Running:
> (fun '(a b a b))
#t
> (fun '(a b a))
#f
> (fun '(a b))
#t
> (fun '(a))
#f
> (fun '())
#t
>
回答3:
So much wheel reinvention. Just use SRFI 1!
(require srfi/1)
(define (fun4 lst)
(every eq? lst (circular-list 'a 'b)))
(This operates under the assumption that (a b a) should be valid rather than invalid.)
来源:https://stackoverflow.com/questions/19393467/a-function-which-will-determine-that-if-a-passed-in-list-follows-an-a-b-pattern