Old MM2 hw #
1
Write a recursive Racket function “sum-alternate” that takes a positive integer x as a parameter.
The function should return the sum of all the integers x, x-2, x-4, x-6, etc, as long as the numbers are positive.
For example, (sum-alternate 5)
should evaluate to 5+3+1, and (sum-alternate 6)
should evaluate to 6+4+2.
(define (sum-acc sum acc)
(if (<= sum 0)
acc
(sum-acc (- sum 2) (+ sum acc))))
(define (sum-alternate sum)
(sum-acc sum 0))
2
Write a recursive Racket function “sum” that takes two integers as parameters, each greater or equal to zero, and evaluates to their sum.
In this problem, you must use the built-in functions add1
and sub1
and may not use the built-in functions “+” or “-”.
For example, (sum 2 3)
should evaluate to 5.
Note: (add1 5)
evaluates to 6 and (sub1 4)
evaluates to 3.
Hint: like you saw in the “append” lecture, treat one of the parameters as the size of the problem and recurse until it reaches your base case.
(define (sum-acc a b acc)
(cond ((> a 0) (sum-acc (sub1 a) b (add1 acc)))
((> b 0) (sum-acc a (sub1 b) (add1 acc)))
(else acc)))
(define (sum a b)
(sum-acc a b 0))
3
Write a recursive Racket function “remove-char” that takes two string parameters, s and c, and evaluates to string s with all occurrences of c removed.
The string c is guaranteed to be a length-1 string; in other words a single character string.
For example (remove-char "abc" "b")
should evaluate to “ac”.
Here is pseudocode that you could implement.
if s is empty
return s
else if (c = first char of s)
return remove-char(all but first char of s)
else
return first char of s concatenated with remove-char(all but first char of s)
(define (remove-char s c)
(cond ((string=? s "") s)
((string=? c (substring s 0 1)) (remove-char (substring s 1) c))
(else (string-append (substring s 0 1) (remove-char (substring s 1) c)))))
4
Write a recursive Racket function “all-same” that takes a string as a parameter and evaluates to true iff every character in the string is the same. Note: A string of length 0 or 1 should also evaluate to true.
(define (all-same s)
(cond ((<= (string-length s) 1) #t)
((string=? (substring s 0 1) (substring s 1 2)) (all-same (substring s 1)))
(else #f)))