Reputation: 67
I'm trying to write a Scheme function called "p" with one parameter X which is a list of letters. the function should return true if the number of a's is one less than the number of b's. This is what I have but can't get around argument errors. Any help is greatly appreciated.
#lang scheme
(define p
(lambda (X)
(let ((countA 0))
(let ((countB 0))
(count(countA countB X)
(if (= countA (- countB 1))
#t
#f))))))
(define count
(lambda (A B X)
(if (null? (cdr X))
(car X)
((if (string=? "a" (car X))
((+ A 1) (p(cdr X)))
((if (string=? "b" (car X))
((+ B 1) (p(cdr X)))
(p(cdr X)))))))))
Upvotes: 1
Views: 3816
Reputation: 236004
I'm betting this is a homework. If it weren't, this is the idiomatic way to solve it:
(define (p lst)
(= (count-letters "a" lst)
(- (count-letters "b" lst) 1)))
(define (count-letters letter lst)
(count (lambda (e) (string=? e letter))
lst))
... But of course, you're expected to solve it by hand. Some feedback on your code:
if
let
for this problem is incorrect, it might work if you were mutating the value of the variables defined in the let
s, but I really doubt that's the best approach to write the solution in this casecount
procedure will somehow store the result after count
returns - that's not right, it won't work like thatTake ideas from the above code to write your own solution - first, you need to define a count-letters
function that doesn't use count
and that, for a given letter, counts the number of times it occurs in the list. With that procedure in hand, it's pretty easy to write the p
procedure (in fact, you can just snarf my implementation above!). Don't forget to test it:
(p '("a" "b" "b"))
=> #t
(p '("a" "a" "b" "b"))
=> #f
Upvotes: 1