Check/Compare a value using "in"

Ali Çehreli acehreli at yahoo.com
Fri Nov 2 20:03:29 PDT 2012


On 11/02/2012 06:42 PM, MattCoder wrote:
 > Hi,
 >
 > I need to check if some value exists in a list (Array). To achieve that,
 > I'm using Associative Arrays like this:
 >
 > // Example
 > void main()
 > {
 > int[char] aa = [ '+' : 0, '-' : 1];
 > char ch = '+';
 >
 > if(ch in aa)
 > // doSomething()...
 > }
 >
 > But I'm looking for a more simple way like:
 >
 > if(ch in ['+', '-']) // <- This doesn't works
 > // doSomething()...
 >
 > Or another simple way (if exists of course).
 >
 > Thanks.

This came up in another forum just today. Here is a quick translation of 
my answer there:

import std.stdio;
import std.range;
import std.algorithm;
import std.random;

int[] sortedArray(int length)
{
     return
         iota(0, length)
         .map!(a => uniform(0, length))
         .array
         .sort;
}

void main()
{
     enum size_t length = 100;
     auto numbers = sortedArray(length);

     /* When we have an already-sorted array, the programmatic way of
      * communicating this fact is to call assumeSorted(). assumeSorted()
      * returns a range type of an instatiation of the SortedRange
      * template, but we usually do not need to spell it out. */
     auto knownToBeSortedRange = assumeSorted(numbers);

     /* Some Phobos algorithms already recognize SortedRange and act
      * accordingly when operating on such a range (read: O(log N)
      * instead of O(N)).
      *
      * One such algorithm is equalRange(), which returns the "middle"
      * of the range that matches a criteria: */
     auto needle = length / 2;

     {
         writeln("\n--- with equalRange() ---");
         auto result = knownToBeSortedRange.equalRange(needle);

         if (result.empty) {
             writefln("Failed to find %s", needle);

         } else {
             writefln("Result: %s", result);
         }
     }

     /* When we are not sure whether the range is sorted, we can call
      * find(): */
     {
         writeln("\n--- with find() ---");
         auto result = numbers.find(needle);

         if (result.empty) {
             writefln("Failed to find %s", needle);

         } else {
             writefln("Found at this point: %s", result);
         }
     }
}

Ali



More information about the Digitalmars-d-learn mailing list