list of cons

list of cons

Ranjit_Singh
Advisor Advisor
1,118 Views
3 Replies
Message 1 of 4

list of cons

Ranjit_Singh
Advisor
Advisor

I have a list of real numbers and some numbers repeat, but they are all in increasing order for example (123.12 124.2 125.25 125.28 125.28 127.1 128 128.5 129 130 130 131 132 132.5)

 

How do I get this list ((123.12 . 124.2) (125.25 . 125.28) (125.28 . 127.1) (128 . 128.5) (129 . 130) (130 . 131) (132  .132.5))

 

Tried using mapcar as follows

(mapcar '(lambda (x y) (cons x y)) lstlst (cdr lstlst))

but what I get is this ((123.12 . 124.2) (124.2 . 125.25) (125.25 . 125.28) (125.28 . 125.28) (125.28 . 127.1) (127.1 . 128) (128 . 128.5) (128.5 . 129) (129 . 130) (130 . 130) (130 . 131) (131 . 132) (132 . 132.5)) as you can see now I need to get rid of 2nd, 4th, 6th, 8th etc. members. Any tips? Maybe I can somehow modify the above mapcar to get the right result. Thanks. Infact, the order of original numbers (I mean sorted or not sorted)  does not even matter. All I care is to cons 1st and 2nd memebr, then 3rd and 4th, then 5th and 6th and so on and get me a new list.

 

0 Likes
Accepted solutions (1)
1,119 Views
3 Replies
Replies (3)
Message 2 of 4

patrick_35
Collaborator
Collaborator
Accepted solution

Hi

 

For example ?

(setq lst '(123.12 124.2 125.25 125.28 125.28 127.1 128 128.5 129 130 130 131 132 132.5))

(defun foo (ele)
  (if ele (cons (list (car ele) (cadr ele)) (foo (cddr ele))))
)

(foo lst)

@+

Message 3 of 4

CADaSchtroumpf
Advisor
Advisor

After recursive mode, you have also iterative mode...

(setq lst '(123.12 124.2 125.25 125.28 125.28 127.1 128 128.5 129 130 130 131 132 132.5))
((lambda (l / nwl)
	(while (cdr l)
		(setq nwl (cons (cons (car l) (cadr l)) nwl))
		(setq l (cddr l))
	)
	(reverse nwl)
 )
 lst
)
0 Likes
Message 4 of 4

martti.halminen
Collaborator
Collaborator

Another variant:

 

(defun odds (l)
  ;; picks the odd-numbered items of a list: (1 2 3 4) -> ( 1 3)
  (if (null l)
      nil
      (cons (car l)
            (odds (cddr l)))))


(defun evens (l)
  ;; picks the odd-numbered items of a list: (1 2 3 4) -> (2 4)
  (if (null l)
      nil
      (cons (cadr l)
            (evens (cddr l)))))


(mapcar (function cons) 
                (odds lstlst)
                (evens lstlst))
0 Likes