I have been working in DrRacket, trying to create a "prefix" function (#lang racket). It should take two lists as an input, and should output #t
if pf
is either null, or is equal to the beginning of ls
.
My problem is that my code doesn't seem to return anything at all when pf
is not a prefix of ls
and ls
isn't null. If I replace the #f
in the if statement with something else, like '()
, it will return that properly, but if I try to capture the '()
and give an output based on that instead, it gives results that don't make sense (like saying that '()
isn't null, or that '()
doesn't equal '()
). It seems to have something to do with having an if statement within a cond statement. Could anyone tell me what it's doing, or why? Is it possible to make this code work correctly, or am I going to need to rework it another way?
Thanks for the help!
(define prefix
(lambda (pf ls)
(cond
[(null? pf) #t]
[(null? ls) #f]
[(if (equal? (car pf) (car ls)) (prefix (cdr pf) (cdr ls)) #f)])
))
Having an if
within a cond
condition is usually a sign of doing something wrong. I think you meant to say this:
(define prefix
(lambda (pf ls)
(cond
[(null? pf) #t]
[(null? ls) #f]
[(equal? (car pf) (car ls)) (prefix (cdr pf) (cdr ls))]
[else #f])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With