Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme (Racket) if within cond returns nothing

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)])
      ))
like image 667
user1680546 Avatar asked Feb 20 '23 03:02

user1680546


1 Answers

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])))
like image 95
Chris Jester-Young Avatar answered Feb 28 '23 08:02

Chris Jester-Young