January 20, 2017
Scheme makes is possible to write both versions of
squeeze in a single function:
(define (squeeze str c-or-s) (let ((dels (if (char? c-or-s) (list c-or-s) (string->list c-or-s)))) (list->string (filter (lambda (c) (not (member c dels))) (string->list str)))))
The second argument may be either a character or a string; the
let builds a list of characters to be deleted. Then the target string is converted to a list of characters, each is filtered according to the list of characters to be deleted, and the remaining characters are converted back to a string. The
for is typical of C, the higher-order function
filter is typical of Scheme. I’m biased, but I think the Scheme version is simpler because it doesn’t require the auxiliary variables
j, which can both be a source of error. Here’s the function in action, both ways:
> (squeeze "Programming Praxis" #\P) "rogramming raxis" > (squeeze "Programming Praxis" "aeiou") "Prgrmmng Prxs"
You can run the program at http://ideone.com/pCg02E.
Pages: 1 2