EvOlaNdLuPiZ
EvOlaNdLuPiZ

Reputation: 600

Append two functions recursively with Racket?

I'm using racket language, but i'm having some trouble getting some expected results for a recursive function. My goal is to input an integer n and output the element n times, as a list.

' exclude the ' and the text, #lang racket

; take n (integer) e (scheme) build new list    
; 2 `() -> () ()    
; 3 `a -> a a a    
; 4 `(a) -> (a) (a) (a) (a)

(define (list n e)    
   (if (= n 0) e    
      (append e(list (- n 1) e)) ))

; (list 0 '())   
; prints '()   
; (list 2 '())
; should print '() '()

Upvotes: 0

Views: 724

Answers (1)

pdoherty926
pdoherty926

Reputation: 10349

Your problem would appear to be that append isn't doing what you're expecting it to - it unwraps and discards top-level empty lists. (e.g. (append '(1) '() '(2) '() '(3)) ;; => '(1 2 3)).

So, swapping cons in for append will result in (what I believe to be) the expected output.

(define (my-list n empty-list)    
   (if (= n 0) 
      empty-list    
      (cons 
        empty-list 
        (my-list (- n 1) empty-list))))

(my-list 2 '()) ;; => '(() ())

You should also reconsider clobbering Racket's built-in list function.

This answer has a useful breakdown of what append is doing internally and why it's undesirable in this scenario.

Upvotes: 1

Related Questions