2 Replies - 2815 Views - Last Post: 09 March 2012 - 10:08 AM

#1 Sherlock_S  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 09-March 12

Split a list in Scheme help

Posted 09 March 2012 - 01:06 AM

I am a beginner of scheme and wondering if someone could help me out...

I am trying to split and return a number of sublists at a given element 0; call it (split-Elem list).
(split-Elem '(2 3 0 6 5 1 0 1 0)) => ((2 3) (6 5 1) (1)).

Here is what I have so far:


(define (split-Elem data)
  (if(null? data) '()
      ( let* ((head (car data)) 
             (tail (cdr data)))
        (if(= head 0) (split-Elem tail)  
           ( let *((tail1 (car tail)))
            (if(= tail1 0) (append (list(cons head '())) (split-Elem (cdr tail)))
              (append (list(cons head tail1)) (split-Elem (cdr tail))
  )))))))




What was worse, using this code I get a very wired answer:
(split-Elem '(2 3 0 6 5 1 0 1 0)) => ((2.3) (6.5) (1) (1)).

I have no idea about the error and appreciate any help I could get. Many Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Split a list in Scheme help

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2117
  • View blog
  • Posts: 3,242
  • Joined: 21-June 11

Re: Split a list in Scheme help

Posted 09 March 2012 - 02:06 AM

A proper list is either nil or a cons-cell whose tail is a proper list. When you do (cons head tail1), tail1 is not a proper list (it is a number), so the result is not a proper list. A cons-cell whose second element is not a proper list is called a dotted list. Such cons cells are displayed as (head . tail). That is why your output looks the way it does. You need to change your calls to cons, so that the tail is always a proper list.
Was This Post Helpful? 1
  • +
  • -

#3 Sherlock_S  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 09-March 12

Re: Split a list in Scheme help

Posted 09 March 2012 - 10:08 AM

View Postsepp2k, on 09 March 2012 - 02:06 AM, said:

A proper list is either nil or a cons-cell whose tail is a proper list. When you do (cons head tail1), tail1 is not a proper list (it is a number), so the result is not a proper list. A cons-cell whose second element is not a proper list is called a dotted list. Such cons cells are displayed as (head . tail). That is why your output looks the way it does. You need to change your calls to cons, so that the tail is always a proper list.


Thanks for your help. I change my the last line of my code, now it is
(append (list(cons head (cons tail1 '()))) (split-Elem (cdr tail))



The answer now is a much better way, that is:
(split-Elem '(2 3 0 6 5 1 0 1 0)) => ((2 3) (6 5) (1) (1))
I think there must be some wrong in my recursion, if possible, can you help me to point it out?

Many thanks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1