Tuesday, 21 February 2012

Exercise 156: Use cons and empty to construct lists.


Exercise 156: Use cons and empty to construct the equivalent of the following lists:

; 1) (list 0 1 2 3 4 5)
; 2) (list (list "adam" 0) (list "eve" 1) (list "louisXIV" 2))
; 3) (list 1 (list 1 2) (list 1 2 3))

I found this exercise a little harder than expected. This is because I very quickly got tired of using cons to build up lists and have been using list most of the time.
It's good to have the theory and knowledge of lists being constructed of cons and empty, but in practise it is far too tedious.



1) This is very straight forward - just a list of cons...


(check-expect (cons 0 (cons 1 (cons 2 (cons 3 (cons 4 (cons 5 empty ))))))              
              (list 0 1 2 3 4 5))






2) This is a little more complex - each sublist needs to be cons back into the main list. 


(check-expect (cons (cons "adam" (cons 0 empty))
                    (cons (cons "eve"  (cons 1 empty))
                          (cons (cons "louisXIV" (cons 2 empty)) empty)))
              (list (list "adam" 0) (list "eve" 1) (list "louisXIV" 2)))






3) Again, a little more complex. I found it easier to build this up from the inside.


(check-expect (cons 1 
                    (cons (cons 1 (cons 2 empty)) 
                          (cons (cons 1 (cons 2 (cons 3 empty))) empty)))
              (list 1 (list 1 2) (list 1 2 3)))

No comments:

Post a Comment