2 Replies - 2540 Views - Last Post: 03 April 2012 - 11:27 AM

#1 nacholibre  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 76
  • Joined: 19-September 09

scheme making lists out of a list

Posted 02 April 2012 - 12:34 PM

Hello all.

I am trying to make 2 lists from a list based on the items in the original list
Let the original list be OL '( (item1)(item2)(item3)(node1)(node2)(item4) ) ;its a list of lists
I want to create the following 2 lists
list1 '((item1)(item2)(item3)(item4))
list2 '((node1)(node2))

Here is a map fucntion i wrote to do this
(define list1 null)
(define list2 null)

(map(lambda i)
    (if(item? i) (cons list1 i) (cons list2 i))OL)



item? is just a bool function that returns #t or #f based on i type.
I have noticed when using map; the 'i' is not a list as i expected. How do i fix this map to generate these 2 lists
thanks

Is This A Good Question/Topic? 0
  • +

Replies To: scheme making lists out of a list

#2 GWatt  Icon User is offline

  • member icon

Reputation: 278
  • View blog
  • Posts: 3,079
  • Joined: 01-December 05

Re: scheme making lists out of a list

Posted 02 April 2012 - 07:55 PM

I would use filter for this.
(set! list1 (filter pred? OL))
(set! list2 (filter (lambda (i) (not (pred? i))) OL)



EDIT:
Also, in response to your original question as to why list1 and list2 did not change. cons does not change the 2nd argument. Most scheme functions do not alter the value of their arguments and instead return a new object. By convention, any function that does change its argument(s) will end with a '!'.
Another thing to note is that cons does not need to return a list. All cons does is return a pair where the first and second argument are the first and second value. If you fire up your scheme and type '(cons 1 2)' you'll get something that looks like: '(1 . 2)' The period means that the structure is a cons pair and not a proper list.
I'm telling you this because your code is cons-ing a list onto an item and I think you want to cons an item onto the list.

This post has been edited by GWatt: 02 April 2012 - 08:03 PM

Was This Post Helpful? 1
  • +
  • -

#3 nacholibre  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 76
  • Joined: 19-September 09

Re: scheme making lists out of a list

Posted 03 April 2012 - 11:27 AM

Thank you. Makes sense
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1