Hi! I'm just working on a small problem in Scheme. I am passing to the function a list, such as '(1 2 3), and I need the function to return seperate lists, such as '(1)'(1 2)'(1 2 3). I have already experiemented with many different appends and cons, and I am looking for further advice.

Here is what I have so far...

(define (sublists lst)
  (if (null? lst)
     '()
      (cons (car lst)(sublists (cdr lst)))
     )
)
      
  
(sublists '(1 2 3))

This just returns my original list, and not what I need. Thanks.

Recommended Answers

All 7 Replies

Of course it does. You do recurcively separating each head by car and then cons them back together, what else it could do. Describe the pseudocode with examples what you are trying and by what algorithm.

I am passing to the function a list, such as '(1 2 3), and I need the function to return seperate lists, such as '(1)'(1 2)'(1 2 3).

It's not entirely clear what you want. Are you trying to return all possible sublists, so that (sublists '(1 2 3)) returns ((1) (2) (3) (1 2) (1 3) (2 3) (1 2 3)) ?

I'm trying to return the first element of the list as a list, then move over one spot and return the next element along with the first one. I've tried things such as

(define (sublists lst)
  
  (if (null? lst)
      '()
      (cons (list(car lst))(sublists (cdr lst)))
     )
)
  
(sublists '(1 2 3))

This returns,

(1)(2)(3)

But I want,

(1)(1 2)(1 2 3)

That gives me back 3 separate lists, which is what I want, but they each only have one element. Somehow I need to call the function recursively, while building a list from the beginning.

This gives more natural shared last element result, you can do rest and find how to get it return what you want (you may need accumulator parameter or reverse function):

(define (sublists lst)
   (if (null? lst) '()
        (append (list lst) (sublists (cdr lst)))
    )
)
Lispy version 2.0
lispy> (sublists '(1 2 3 4))
((1 2 3 4) (2 3 4) (3 4) (4))

(run with Norvig's lisp written in Python)

If you know Prolog, you may also notice that output of my function are end parts of difference lists for original lst giving your goal answers, if you replace (1 2 3 4) answer in beginning with () answer in end.
For example
(1 2 3 4)\(2 3 4) = (1)

You'll need to use map or write a recursive function that is like map.

Note that your output requires O(n^2) work to construct, which means you'll need an O(n^2) algorithm here, not one of these obviously-O(n) algorithms.

(define (sublists xs)
 (if (null? xs) ;if the list is null, you're done
	'()
	(append (sublists (reverse (cdr (reverse xs))))(list xs)) 
		
	)
)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.