2010年7月20日火曜日

Goldbach's conjecture

;; P40 (**) Goldbach's conjecture.
;; Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer.
;; Example:
;; * (goldbach 28)
;; (5 23)
#lang racket
(provide goldbach)
(require "p39.ss")
(define (goldbach n)
(and (> n 2) (even? n)
(let loop ((lst (eratosthenes n)))
(let ((i (car lst)))
(let ((j (- n i)))
(if (member j lst)
`(,i ,j)
(loop (cdr lst))))))))
view raw p40.ss hosted with ❤ by GitHub

A list of prime numbers

;; P39 (*) A list of prime numbers.
;; Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.
#lang racket
(provide (all-defined-out))
(require srfi/1)
(define (eratosthenes n)
(let loop ((lst (iota n 3)) (acc '(2)))
(let ((i (car acc)))
(if (< (apply max lst) (expt i 2))
(append (reverse acc) lst)
(let ((lst (remove (lambda (x)
(zero? (modulo x i)))
lst)))
(loop (cdr lst) (cons (car lst) acc)))))))
(define (p39 m n)
(remove (lambda (x)
(< x m))
(eratosthenes n)))
view raw p39.ss hosted with ❤ by GitHub

Compare the two methods of calculating Euler's totient function

;; P38 (*) Compare the two methods of calculating Euler's totient function.
;; Use the solutions of problems P34 and P37 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate phi(10090) as an example.
> (time (phi 10090))
cpu time: 0 real time: 1 gc time: 0
4032
> (time (totient-phi 10090))
cpu time: 4 real time: 4 gc time: 0
4032
>
view raw p38.ss hosted with ❤ by GitHub

Calculate Euler's totient function phi(m) (improved)

;; P37 (**) Calculate Euler's totient function phi(m) (improved).
;; See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem P36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula:
;; phi(m) = (p1 - 1) * p1 ** (m1 - 1) + (p2 - 1) * p2 ** (m2 - 1) + (p3 - 1) * p3 ** (m3 - 1) + ...
;; Note that a ** b stands for the b'th power of a.
(require "p36.ss")
(define (phi m)
(let loop ((lst (prime-factors-mult m))
(acc 1))
(if (null? lst)
acc
(let ((p (caar lst))
(m (- (cadar lst) 1)))
(loop (cdr lst)
(* (- p 1) (expt p m) acc))))))
view raw p37.ss hosted with ❤ by GitHub

Determine the prime factors of a given positive integer (2)

;; P36 (**) Determine the prime factors of a given positive integer (2).
;; Construct a list containing the prime factors and their multiplicity.
;; Example:
;; * (prime-factors-mult 315)
;; ((3 2) (5 1) (7 1))
;; Hint: The problem is similar to problem P13.
#lang racket
(provide prime-factors-mult)
(require "p10.ss")
(require "p35.ss")
(define (prime-factors-mult n)
(map reverse (encode (prime-factors n))))
view raw p36.ss hosted with ❤ by GitHub

Determine the prime factors of a given positive integer

;; P35 (**) Determine the prime factors of a given positive integer.
;; Construct a flat list containing the prime factors in ascending order.
;; Example:
;; * (prime-factors 315)
;; (3 3 5 7)
#lang racket
(provide prime-factors)
(require "p31.ss")
(define (prime-factors n)
(let loop ((x n) (y 2) (acc '()))
(cond
((= x 1)
(reverse acc))
((and (is-prime? y) (zero? (modulo x y)))
(loop (/ x y) 2 (cons y acc)))
(else
(loop x (+ y 1) acc)))))
view raw p35.ss hosted with ❤ by GitHub

Calculate Euler's totient function phi(m)

;; P34 (**) Calculate Euler's totient function phi(m).
;; Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m.
;; Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.
;; * (totient-phi 10)
;; 4
;; Find out what the value of phi(m) is if m is a prime number. Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later).
(require "p33.ss")
(define (totient-phi m)
(let loop ((r 1) (acc '()))
(if (> r m)
(length acc)
(loop (+ 1 r)
(if (coprime? r m)
(cons r acc)
acc)))))
view raw p34.ss hosted with ❤ by GitHub

Determine whether two positive integer numbers are coprime

;; P33 (*) Determine whether two positive integer numbers are coprime.
;; Two numbers are coprime if their greatest common divisor equals 1.
;; Example:
;; * (coprime 35 64)
;; T
#lang racket
(provide coprime?)
(define (coprime? a b)
(= 1 (gcd a b)))
view raw p33.ss hosted with ❤ by GitHub

Determine the greatest common divisor of two positive integer numbers

;; P32 (**) Determine the greatest common divisor of two positive integer numbers.
;; Use Euclid's algorithm.
;; Example:
;; * (gcd 36 63)
;; 9
(define (gcd a b)
(let loop ((x a) (y b) (z 1) (w 0))
(let ((q (quotient x y)) (r (modulo x y)))
(if (zero? r)
y
(loop y r w (- z (* q w)))))))
view raw p32.ss hosted with ❤ by GitHub

Determine whether a given integer number is prime

;; P31 (**) Determine whether a given integer number is prime.
;; Example:
;; * (is-prime 7)
;; T
#lang racket
(provide is-prime?)
(define (is-prime? n)
(and (> n 1)
(or (= n 2)
(and (not (zero? (modulo n 2)))
(let loop ((i 3))
(or (> (* i i) n)
(and (not (zero? (modulo n i)))
(loop (+ i 2)))))))))
view raw p31.ss hosted with ❤ by GitHub

2010年7月19日月曜日

Sorting a list of lists according to length of sublists

;; P28 (**) Sorting a list of lists according to length of sublists
;; a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa.
;; Example:
;; * (lsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o)))
;; ((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L))
;; b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their length frequency; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later.
;; Example:
;; * (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o)))
;; ((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n))
;; Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears twice (there are two list of this length). And finally, the last three lists have length 2. This is the most frequent length.
(define (lsort lst)
(sort lst (lambda (x y)
(< (length x) (length y)))))
(define (lfmark lst)
(let loop ((old lst) (acc '()))
(if (null? old)
(reverse acc)
(let ((head (car old)))
(loop (cdr old)
(cons
`(,(lfreq lst (length head))
,head)
acc))))))
(define (lfunmark lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(loop (cdr lst)
(cons (second (car lst)) acc)))))
(define (lfreq lst len)
(let loop ((lst lst) (acc 0))
(if (null? lst)
acc
(loop (cdr lst)
(+ (if (= (length (car lst)) len)
1
0) acc)))))
(define (lfsort lst)
(let ((lst (lfmark lst)))
(lfunmark (sort lst (lambda (x y)
(< (car x) (car y)))))))
view raw p28.ss hosted with ❤ by GitHub

Group the elements of a set into disjoint subsets

;; P27 (**) Group the elements of a set into disjoint subsets.
;; a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list.
;; Example:
;; * (group3 '(aldo beat carla david evi flip gary hugo ida))
;; ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )
;; ... )
;; b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups.
;; Example:
;; * (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5))
;; ( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )
;; ... )
;; Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...). However, we make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...).
;; You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients".
(require "p07.ss")
(require "p26.ss")
(define (remove-list old new)
(if (null? new)
old
(remove-list (remove (car new) old) (cdr new))))
(define (group-n num result old)
(combination-aux
result
(combination num
(remove-list old
(flatten result)))))
(define (group-n-aux num result lst)
(let loop ((result result) (acc '()))
(if (null? result)
acc
(let ((head (car result))
(tail (cdr result)))
(loop tail
`(,@acc ,@(group-n num head lst)))))))
(define (group3 lst)
(group-n-aux 4
(group-n-aux 3
(group-n 2 '() lst)
lst)
lst))
(define (group old new)
(if (null? (cdr new))
(group-n (car new) '() old)
(let ((lst (reverse new)))
(group-n-aux (car lst)
(group old (reverse (cdr lst)))
old))))
view raw p27.ss hosted with ❤ by GitHub

Generate the combinations of K distinct objects chosen from the N elements of a list

;; P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list
;; In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list.
;; Example:
;; * (combination 3 '(a b c d e f))
;; ((A B C) (A B D) (A B E) ... )
#lang racket
(provide (all-defined-out))
(require "p17.ss")
(define (combination n lst)
(let ((num (- n 1)))
(let loop ((lst lst) (acc '()))
(if (or (> num (length lst)) (< n 2))
acc
(let ((ls0 (split num lst))
(ls1 (split-after num lst)))
(loop (cdr lst)
`(,@acc ,@(combination-aux ls0 ls1))))))))
(define (combination-aux new old)
(let loop ((lst old) (acc '()))
(if (null? lst)
acc
(loop (cdr lst)
`(,@acc (,@new ,(car lst)))))))
view raw p26.ss hosted with ❤ by GitHub

Generate a random permutation of the elements of a list

;; P25 (*) Generate a random permutation of the elements of a list.
;; Example:
;; * (rnd-permu '(a b c d e f))
;; (B A D C E F)
;; Hint: Use the solution of problem P23.
(require "p23.ss")
(define (rnd-permu lst)
(rnd-select lst (length lst)))
view raw p25.ss hosted with ❤ by GitHub

Lotto: Draw N different random numbers from the set 1..M

;; P24 (*) Lotto: Draw N different random numbers from the set 1..M.
;; The selected numbers shall be returned in a list.
;; Example:
;; * (lotto-select 6 49)
;; (23 1 17 33 21 37)
;; Hint: Combine the solutions of problems P22 and P23.
(require "p22.ss")
(require "p23.ss")
(define (lotto-select num max-elm)
(rnd-select (range 1 max-elm) num))
view raw p24.ss hosted with ❤ by GitHub

Extract a given number of randomly selected elements from a list

;; P23 (**) Extract a given number of randomly selected elements from a list.
;; The selected items shall be returned in a list.
;; Example:
;; * (rnd-select '(a b c d e f g h) 3)
;; (E D A)
;; Hint: Use the built-in random number generator and the result of problem P20.
#lang racket
(provide rnd-select)
(require "p03.ss")
(require "p20.ss")
(define (rnd-select lst num)
(let loop ((lst lst) (selected 0) (acc '()))
(if (= num selected)
(reverse acc)
(let ((rand-pos (+ (random (length lst)) 1)))
(loop (remove-at lst rand-pos)
(+ selected 1)
(cons (element-at lst rand-pos) acc))))))
view raw p23.ss hosted with ❤ by GitHub

Create a list containing all integers within a given range

;; P22 (*) Create a list containing all integers within a given range.
;; If first argument is smaller than second, produce a list in decreasing order.
;; Example:
;; * (range 4 9)
;; (4 5 6 7 8 9)
#lang racket
(provide range)
(define (range ini fin)
(let ((proc (if (> ini fin) - +)))
(let loop ((i ini) (acc '()))
(let ((cia (cons i acc)))
(if (= i fin)
(reverse cia)
(loop (proc i 1) cia))))))
view raw p22.ss hosted with ❤ by GitHub

Insert an element at a given position into a list

;; P21 (*) Insert an element at a given position into a list.
;; Example:
;; * (insert-at 'alfa '(a b c d) 2)
;; (A ALFA B C D)
(define (insert-at elm lst pos)
(let loop ((lst lst) (pos pos) (acc '()))
(if (or (= pos 1) (null? lst))
(append (reverse acc) (cons elm lst))
(loop (cdr lst) (- pos 1) (cons (car lst) acc)))))
view raw p21.ss hosted with ❤ by GitHub

2010年7月15日木曜日

Remove the K'th element from a list

;; P20 (*) Remove the K'th element from a list.
;; Example:
;; * (remove-at '(a b c d) 2)
;; (A C D)
#lang racket
(provide remove-at)
(define (remove-at lst pos)
(let loop ((lst lst) (ini 1) (acc '()))
(let ((tail (cdr lst)))
(if (= pos ini)
(append (reverse acc) tail)
(loop tail (+ ini 1) (cons (car lst) acc))))))
view raw p20.ss hosted with ❤ by GitHub

Rotate a list N places to the left

;; P19 (**) Rotate a list N places to the left.
;; Examples:
;; * (rotate '(a b c d e f g h) 3)
;; (D E F G H A B C)
;; * (rotate '(a b c d e f g h) -2)
;; (G H A B C D E F)
;; Hint: Use the predefined functions length and append, as well as the result of problem P17.
(require "p17.ss")
(define (rotate lst x)
(define (proc arg)
(if (negative? x)
(reverse arg)
arg))
(let ((ls (split (proc lst) (abs x))))
(let ((head (car ls)) (tail (cadr ls)))
(proc (append tail head)))))
view raw p19.ss hosted with ❤ by GitHub

Extract a slice from a list

;; P18 (**) Extract a slice from a list.
;; Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1.
;; Example:
;; * (slice '(a b c d e f g h i k) 3 7)
;; (C D E F G)
(require srfi/1)
(define (slice lst i k)
(drop (take lst k) (- i 1)))
view raw p18.ss hosted with ❤ by GitHub

Split a list into two parts; the length of the first part is given

;; P17 (*) Split a list into two parts; the length of the first part is given.
;; Do not use any predefined predicates.
;; Example:
;; * (split '(a b c d e f g h i k) 3)
;; ( (A B C) (D E F G H I K))
#lang racket
(provide (all-defined-out))
(require srfi/1)
(define (split pos lst)
(take lst pos))
(define (split-after pos lst)
(drop lst pos))
view raw p17.ss hosted with ❤ by GitHub

Drop every N'th element from a list

;; P16 (**) Drop every N'th element from a list.
;; Example:
;; * (drop '(a b c d e f g h i k) 3)
;; (A B D E G H K)
(define (drop lst x)
(let loop ((lst lst) (i 1) (acc '()))
(let ((revacc (reverse acc)))
(if (null? lst)
revacc
(let ((tail (cdr lst)))
(cond ((< (length lst) x)
(append revacc tail))
((= i x)
(loop tail 1 acc))
(else
(loop tail (+ 1 i) (cons (car lst) acc)))))))))
view raw p16.ss hosted with ❤ by GitHub

Replicate the elements of a list a given number of times

;; P15 (**) Replicate the elements of a list a given number of times.
;; Example:
;; * (repli '(a b c) 3)
;; (A A A B B B C C C)
(define (repli lst int)
(let loop ((lst lst) (i int) (acc '()))
(cond ((null? lst) (reverse acc))
((< i 1) (loop (cdr lst) int acc))
(else (loop lst (- i 1) (cons (car lst) acc))))))
view raw p15.ss hosted with ❤ by GitHub

Duplicate the elements of a list

;; P14 (*) Duplicate the elements of a list.
;; Example:
;; * (dupli '(a b c c d))
;; (A A B B C C C C D D)
(define (dupli lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(let ((head (car lst)))
(loop (cdr lst)
(append `(,head ,head) acc))))))
view raw p14.ss hosted with ❤ by GitHub

Run-length encoding of a list (direct solution)

;; P13 (**) Run-length encoding of a list (direct solution).
;; Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.
;; Example:
;; * (encode-direct '(a a a a b c c a a d e e e e))
;; ((4 A) B (2 C) (2 A) D (4 E))
;; Basd on the implementation of Paul Graham's ANSI Common Lisp
(define (encode-direct x)
(if (pair? x)
(compress (car x) 1 (cdr x))
x))
(define (compress elt n lst)
(let loop ((elt elt) (n n) (lst lst) (acc '()))
(let ((cna (cons (n-elts elt n) acc)))
(if (null? lst)
(reverse cna)
(let ((next (car lst))
(tail (cdr lst)))
(if (eq? next elt)
(loop elt (+ n 1) tail acc)
(loop next 1 tail cna)))))))
(define (n-elts elt n)
(if (> n 1)
`(,n ,elt)
elt))
view raw p13.ss hosted with ❤ by GitHub

Decode a run-length encoded list

;; P12 (**) Decode a run-length encoded list.
;; Given a run-length code list generated as specified in problem P11. Construct its uncompressed version.
(define (decode lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(let ((head (car lst)))
(loop (cdr lst) (append
(if (pair? head)
(decode-aux head)
`(,head)) acc))))))
(define (decode-aux lst)
(let ((n (car lst)) (symb (cadr lst)))
(let loop ((n n) (acc '()))
(if (zero? n)
acc
(loop (- n 1) (cons symb acc))))))
view raw p12.ss hosted with ❤ by GitHub

Modified run-length encoding

;; P11 (*) Modified run-length encoding.
;; Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.
;; Example:
;; * (encode-modified '(a a a a b c c a a d e e e e))
;; ((4 A) B (2 C) (2 A) D (4 E))
(require srfi/1)
(define (encode lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(loop (strip lst)
(cons
(let ((head (car lst))
(len (length (picks lst))))
(if (= len 1)
head
`(,len ,head)))
acc)))))
(define-syntax define-encode-aux
(syntax-rules ()
((_ name proc)
(define (name lst)
(let ((head (car lst)))
(proc (lambda (x)
(eq? head x)) lst))))))
;; Using a procedure, take-while, defined in SRFI-1
(define-encode-aux picks take-while)
;; Using a procedure, drop-while, defined in SRFI-1
(define-encode-aux strip drop-while)
view raw p11.ss hosted with ❤ by GitHub

Run-length encoding of a list

;; P10 (*) Run-length encoding of a list.
;; Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.
;; Example:
;; * (encode '(a a a a b c c a a d e e e e))
;; ((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))
#lang racket
(provide encode)
(require srfi/1)
(define (encode lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(loop (strip lst)
(cons
`(,(length (picks lst)) ,(car lst))
acc)))))
(define-syntax define-encode-aux
(syntax-rules ()
((_ name proc)
(define (name lst)
(let ((head (car lst)))
(proc (lambda (x)
(eq? head x)) lst))))))
;; Using a procedure, take-while, defined in SRFI-1
(define-encode-aux picks take-while)
;; Using a procedure, drop-while, defined in SRFI-1
(define-encode-aux strip drop-while)
view raw p10.ss hosted with ❤ by GitHub

Pack consecutive duplicates of list elements into sublists

;; P09 (**) Pack consecutive duplicates of list elements into sublists.
;; If a list contains repeated elements they should be placed in separate sublists.
;; Example:
;; * (pack '(a a a a b c c a a d e e e e))
;; ((A A A A) (B) (C C) (A A) (D) (E E E E))
(require srfi/1)
(define (pack lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(loop (strip lst) (cons (picks lst) acc)))))
(define-syntax define-pack-aux
(syntax-rules ()
((_ name proc)
(define (name lst)
(let ((head (car lst)))
(proc (lambda (x)
(eq? head x)) lst))))))
;; Using a procedure, take-while, defined in SRFI-1
(define-pack-aux picks take-while)
;; Using a procedure, drop-while, defined in SRFI-1
(define-pack-aux strip drop-while)
view raw p09.ss hosted with ❤ by GitHub

Eliminate consecutive duplicates of list elements

;; P08 (**) Eliminate consecutive duplicates of list elements.
;; If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
;; Example:
;; * (compress '(a a a a b c c a a d e e e e))
;; (A B C A D E)
(define (compress lst)
(if (null? lst)
'()
(let loop ((lst lst) (acc '()))
(let ((head (car lst)) (tail (cdr lst)))
(let ((cha (cons head acc)))
(if (null? tail)
(reverse cha)
(loop tail (if (eq? head (car tail)) acc cha))))))))
view raw p08.ss hosted with ❤ by GitHub

Flatten a nested list structure

;; P07 (**) Flatten a nested list structure.
;; Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).
;; Example:
;; * (my-flatten '(a (b (c d) e)))
;; (A B C D E)
;; Hint: Use the predefined functions list and append.
(define (my-flatten lst)
(if (null? lst)
'()
(let ((head (car lst)) (flat-tail (my-flatten (cdr lst))))
(append ((if (pair? head) my-flatten list) head) flat-tail))))
view raw p07.ss hosted with ❤ by GitHub

Find out whether a list is a palindrome

;; P06 (*) Find out whether a list is a palindrome.
;; A palindrome can be read forward or backward; e.g. (x a m a x).
(define (palin? lst)
(equal? lst (reverse lst)))
view raw p06.ss hosted with ❤ by GitHub

Reverse a list

;; P05 (*) Reverse a list.
(define (reverses lst)
(let loop ((lst lst ) (acc '()))
(if (null? lst)
acc
(loop (cdr lst) (cons (car lst) acc)))))
view raw p05.ss hosted with ❤ by GitHub

Find the number of elements of a list

;; P04 (*) Find the number of elements of a list.
(define (longitude lst)
(let loop ((lst lst) (acc 0))
(if (null? lst)
acc
(loop (cdr lst) (+ 1 acc)))))
view raw p04.ss hosted with ❤ by GitHub

Find the K'th element of a list

;; P03 (*) Find the K'th element of a list.
;; The first element in the list is number 1.
;; Example:
;; * (element-at '(a b c d e) 3)
;; C
#lang racket
(provide element-at)
(define (element-at lst n)
(list-ref lst (- n 1)))
view raw p03.ss hosted with ❤ by GitHub

Find the last but one box of a list

;; P02 (*) Find the last but one box of a list.
;; Example:
;; * (my-but-last '(a b c d))
;; (C D)
(define (my-but-last lst)
(let ((revlis (reverse lst)))
(cond
((null? revlis) '())
((< (length revlis) 3) lst)
(else `(,(cadr revlis) ,(car revlis))))))
view raw p02.ss hosted with ❤ by GitHub

Find the last box of a list

;; P01 (*) Find the last box of a list.
;; Example:
;; * (my-last '(a b c d))
;; (D)
(define (my-last lst)
(if (null? lst)
'()
(let ((tail (cdr lst)))
(if (null? tail)
lst
(my-last tail)))))
view raw p01.ss hosted with ❤ by GitHub