Reputation: 23
Ok, I am really really bad at scheme and I keep getting stuck on this function (watch it be a really easy fix). I am trying to write a function on whether or not a list input is a bag (a bag being a list of tuples where the first number in the tuple is the value and the second number is the cardinality, also each value should never be repeated and be sorted from least to greatest). This is what I have... syntax is probably horrible...
(define (bag? qbag)
(cond ((null? qbag) #t)
(if(eqv? (pair? (car qbag)) #t)
(baghelp (cdr qbag) (car(car qbag))))
(else (#f))))
(define (baghelp qbag x)
(cond((null? qbag) #t)
(if(and(if (eqv? (pair? (car qbag)) #t))
(if (< x (car(car qbag)))))
(baghelp (cdr qbag) (car(car qbag)))
(else(#f)))))
sample input output:
(bag? '((0 1)))
#f
(bag? '())
#t
(bag? '10)
#f
(bag? '((5 2) (4 3)))
#f
(bag? '((5 2) (7 3)))
#t
(bag? '((5 1 0)))
#f
(bag? '((5 5) (5 2)))
#f
Upvotes: 0
Views: 125
Reputation: 18917
Yes your syntax is quite bad. The way you use of if
inside cond
and expressions like (#f)
makes me think that you have avoided Scheme literature until now... really, read a good tutorial, that's a must.
Here's an example of how I would write this (more or less; I would factor out the repetitive uses of (car bag)
and (caar bag)
but this way it's probably more readable to you):
(define (bag? bag)
(and (list? bag) (bag-help bag '())))
(define (bag-help bag last-val)
(or (null? bag)
(and (list? (car bag))
(> (caar bag) 0)
(= 2 (length (car bag)))
(or (null? last-val) (< last-val (caar bag)))
(bag-help (cdr bag) (caar bag)))))
This passes all your tests and has the additional contraints you mentioned in the comments.
Upvotes: 2