Scheme and Smalltalk -  Programming Exercises April 6

Program in Scheme:
1. Given a list, return a list with its 2nd element deleted. 

2.Given a list, return a list with its nth element deleted.

Program in Smalltalk
3. Given an integer i and a list L, cycle L to the left i times.

4. Duplicate each element of a list.



Gnu Smalltalk versions for 1 and 2
! Object methodsFor: 'algorithms' !

delete2nd
	^((OrderedCollection with: self first), (self copyFrom: 3 )).

!

deleteNth: lis
	(lis size = 0) ifTrue: [ ^lis]
		ifFalse: [
			(self = 0) ifTrue: [ ^(lis copyFrom: 2)]
				ifFalse: [
    " Use Transcript lines for debugging...
	Transcript show: 'n= ', self printString, ' temp= ', lis printString;cr.
      "
    ^((OrderedCollection with: (lis first)),  ((self - 1) deleteNth: (lis copyFrom: 2 ))).
  			].
		].
!!

Sample runs:

st> FileStream fileIn: 'exercises2GNU.st'!
FileStream
st> #(3 4 5 6 7) delete2nd printNl!
OrderedCollection (3 5 6 7 )

st> (4 deleteNth: #(2 3 4 5 6 76)) printNl!
n= 4 temp= (2 3 4 5 6 76 )
n= 3 temp= (3 4 5 6 76 )
n= 2 temp= (4 5 6 76 )
n= 1 temp= (5 6 76 )
OrderedCollection (2 3 4 5 76 )



Scheme versions of 3 and 4.

(define (duplicate lis)
  (cond ((null? lis) lis)
        (else (cons (car lis) (cons (car lis) (duplicate (cdr lis)))))))

(define (cycle lis n)
  (cond ((= n 0) lis)
        (else (cycle (append (cdr lis) (list (car lis))) (- n 1)))))


Sample Runs:
> (duplicate '(2 3 4 5 6 7 78))
(2 2 3 3 4 4 5 5 6 6 7 7 78 78)
> (cycle '(2 3 4 5 56 6 7) 4)
(56 6 7 2 3 4 5)



Squeak Smalltalk versions of  1 and 2:
! Object methodsFor: 'algorithms' !
delete2nd
		
	^((OrderedCollection with: self first), (self copyFrom: 3 to: self size)).

!

deleteNth: lis
	(lis size = 0) ifTrue: [ ^lis]
	ifFalse: [
		(self = 0) ifTrue: [ ^(lis copyFrom: 2 to: (lis size))]
		ifFalse: [ 
    Transcript show: 'n= ', self printString, ' temp= ', temp printString;cr.
			^((OrderedCollection with: (lis first)),
			   (self-1 deleteNth: (lis copyFrom: 2 to: lis size))).
			].
	].

!

Note: for the cdr of a list, Squeak also has 

	lis allButFirst

In the examples above I'm using

	lis copyFrom:  to: