"Consume", "Skip", "Eat", "Munch", "Bite", or...?

Michel Fortin michel.fortin at michelf.com
Sat Feb 20 15:59:08 PST 2010


On 2010-02-20 15:48:10 -0500, Andrei Alexandrescu 
<SeeWebsiteForEmail at erdani.org> said:

> To focus the discussion about naming conventions, let's discuss one 
> particular aspect. Right now we have in std.algorithm:
> 
> =======================
> /**
> If the range $(D doesThisStart) starts with $(I any) of the $(D
> withOneOfThese) ranges or elements, returns 1 if it starts with $(D
> withOneOfThese[0]), 2 if it starts with $(D withOneOfThese[1]), and so
> on. If no match, returns 0.
> 
> Example:
> ----
> assert(startsWith("abc", ""));
> assert(startsWith("abc", "a"));
> assert(!startsWith("abc", "b"));
> assert(startsWith("abc", 'a', "b") == 1);
> assert(startsWith("abc", "b", "a") == 2);
> assert(startsWith("abc", "a", "a") == 1);
> assert(startsWith("abc", "x", "a", "b") == 2);
> assert(startsWith("abc", "x", "aa", "ab") == 3);
> assert(startsWith("abc", "x", "aaa", "sab") == 0);
> assert(startsWith("abc", "x", "aaa", 'a', "sab") == 3);
> ----
>   */
> uint startsWith(alias pred = "a == b", Range, Ranges...)
> (Range doesThisStart, Ranges withOneOfThese);
> =======================
> 
> I also defined recently:
> 
> =======================
> /**
> If $(D startsWith(r1, r2)), consume the corresponding elements off $(D
> r1) and return $(D true). Otherwise, leave $(D r1) unchanged and
> return $(D false).
>   */
> bool startsWithConsume(R1, R2)(ref R1 r1, R2 r2);
> =======================
> 
> There are a few other functions like that: one version takes a range by 
> value, the other takes it by reference and alters it.
> 
> The question is, what is a good naming convention for expressing that? 
> Other examples: findConsume, consumeFind.

Instead of "startsWithConsume" you could use "consumePrefix" which 
sounds better. You could change "startsWith" to "hasPrefix" too to keep 
things consistent, even though "startsWith" isn't a bad name in itself.

The small string parsing module I made has "consumeUntil" that consumes 
until a predicate tells it to stop.

In fact, all my consuming primitives advancing over the string and 
returning a boolean starts with "consume", this makes their role very 
clear. I also have a "read" family of function that uses consumers as 
predicate to extract consumed strings return them. So I can write fun 
things like this:

	alias isChar!(' ') isSpace;
	alias isNotChar!(' ') isNotSpace;
	alias consumeOneWhile!(isNotSpace) consumeWord;
	alias consumeOneWhile!(isSpace) consumeSpaces;
	alias read!(consumeWord) readWord;
	
	string a = "hello world  of fear  ! ";
	string[] result = readSplit!(readWord, consumeSpaces)(a);
	assert(result == ["hello", "world", "of", "fear", "!"]);


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list