Source
Girl Develop It San Francisco,
Teaching Materials,
Exercises: Strings: MixUp
Description
Given two strings s1 and s2 and an integer n, swap the first n
characters of s1 and s2 and concatenate the results, separated by
a space. If either string is less than or equal to n characters in
length, return them unmodified but concatenated, separated by a space.
| 1
2
 | 'foo', 'bar', 3 ⟹ 'foo bar'
'foobar', 'bazqux', 3 ⟹ 'bazbar fooqux'
 | 
My solution
| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 | #lang racket
(define (headswap s1 s2 n)
  (local [(define (ltn? s)
            (<= (string-length s) n))
          (define SHORT
            (or (ltn? s1) (ltn? s2)))
          (define (swap a b)
            (string-append
              (substring a 0 n) (substring b n)))]
    (cond [SHORT (string-append s1 " " s2)]
          [else
            (string-append
              (swap s2 s1) " " (swap s1 s2))])))
(provide headswap)
 | 
Tests
| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 | #lang racket
(require rackunit rackunit/text-ui "headswap.rkt")
(define headswap-tests
  (test-suite "headswap tests"
  
    (test-case "Should leave strings unmodified"
        (check-equal? (headswap "foo" "bar" 3) "foo bar"))
    (test-case "Should modify strings"
        (check-equal? (headswap "foobar" "bazqux" 3) "bazbar fooqux"))
    ))
(run-tests headswap-tests)
 |