TypeFunction example: ImplictConvTargets

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Oct 6 23:39:24 UTC 2020


On Tue, Oct 06, 2020 at 11:16:47PM +0000, claptrap via Digitalmars-d wrote:
[...]
> If someone said to you "I have this list of integers and I want to get
> a new list containing the ones are divisible by a specific value",
> would you write this...
> 
> ----
> 
> int[] vals = [4,7,28,23,585,73,12];
> 
> int[] getMultiplesX(int i, int candidate, int[] candidates)
> {
>     int[] result;
>     if ((candidate % i) == 0)
>         result ~= candidate;
>     if (candidates.length > 0)
>         return result ~ getMultiplesX(i, candidates[0], candidates[1..$]);
>     else
>        return result;
> }
> 
> int[]  getMultiplesOf(int i)
> {
>     return getMultiplesX(i, vals[0], vals[1..$]);
> }
> 
> ----
> 
> Or would you write it like this...
> 
> int[] vals = [4,7,28,23,585,73,12];
> 
> int[] getMultiplesOf(int i)
> {
>     int[] result;
>     foreach(v; vals)
>         if ((v % i) == 0) result ~= v;
>     return result;
> }

I would write it like this:

	int[] vals = [4,7,28,23,585,73,12];
	
	int[] getMultiplesOf(int i)
	{
	    return vals.filter!(v => (v % i) == 0).array;
	}

One line vs. 4, even more concise. ;-)

Thing is, what someone finds intuitive or not, is a pretty subjective
matter, and depends on what programming style he's familiar with and/or
prefers.  What a C programmer finds readable and obvious may be
needlessly arcane to a Java programmer, and what an APL programmer finds
totally obvious may be completely impenetrable to anyone else. :-P

If we're going to argue over merits, it would really help resolve
matters if we stuck to things that are objectively measurable, since
reasonable people are going to disagree on the subjective points.


T

-- 
Being able to learn is a great learning; being able to unlearn is a greater learning.


More information about the Digitalmars-d mailing list