Exercise 2-4
January 20, 2017
I’m enjoying these small exercises from The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie. We’ll do another one today.
In Section 2.8, Kernighan and Ritchie give a function squeeze
that deletes all characters c
from a string s
:
/* squeeze: delete all c from s */ void squeeze(char s[], int c) { int i, j; for (i = j = 0; s[i] != '\0'; i++) if (s[i] != c) s[j++] = s[i]; s[j] '\0'; }
Then, in Exercise 2-4, they ask the reader to “Write an alternate version of squeeze(s1,s2)
that deletes each character in s1
that matches any character in the string s2
.”
Your task is to write both versions of squeeze
in your favorite language; if you choose C, half the work is already done. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
As a perl user I would do this a perl way…
Perl golf would get it down to
Here’s some C++:
Or some more traditional C:
Guile:
(define (squeeze str chars) (string-delete (string->char-set chars) str))
Python strings have translation-table methods.
Here’s a Haskell version. It also works on any list whose elements support equality testing.
@Globules: I was going to suggest
but really that is just your solution with mfilter instead of filter.
@matthew Your MonadPlus suggestion made me wonder what was the “most general” type I could give it. But then I got lost in a maze of twisty little typeclasses (Foldable, Alternative, etc.) and now I will just go to bed… :-)