Man Person
Man Person

Reputation: 1130

My recursive function is not returning anything, why?

So I'm very new to scheme, first day programming in it. I'm trying to make a recursive function that basically takes two arguements numlist, num numlist is a list of numbers, and num is a single number. The function takes the list, goes through each element and compares it to num, if the number is greater then num it replaces it in the list with a 1, otherwise it replaces it with a 0.

Ex: arguments( (1,2,3,4,5,6,7,8,9,10) , 5) transforms the list to (0,0,0,0,0,1,1,1,1,1)

But for some reason my function is not returning anything, it doesn't print anything to my screen, why?

(define (greater-nums-in-list numlist num)
    (cond
    [(null? numlist) ()]
    [(> (car numlist) num) (append 1 (greater-nums-in-list((cdr numlist) num))]
    [else (append 0 (greater-nums-in-list((cdr numlist) num)))]
    )
)

Any help would be appreciated, this is just personal studying code so I'm in no rush.

Upvotes: 0

Views: 61

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

The "nothing" that it prints to screen is because of the base-condition at the bottom of the recursion:

[(null? numlist) ()]

This means that when you've done iterating the list, you return () - that's not an empty-list - that applying "nothing", an empty list is '().

There were a couple of brackets-bugs and you cannot append 1 or 0 to a list - you need to wrap them in a list first:

(define (greater-nums-in-list numlist num)
  (cond
    [(null? numlist) '()]
    [(> (car numlist) num) (append '(1) (greater-nums-in-list (cdr numlist) num))]
    [else (append '(0) (greater-nums-in-list (cdr numlist) num))]
    )
  )

Usage

>  (greater-nums-in-list '(1 2 3 4) 2)
'(0 0 1 1)
> (greater-nums-in-list '(1 2 3 4 5 6 7 8 9 10) 5)
'(0 0 0 0 0 1 1 1 1 1)
> 

Upvotes: 1

Related Questions