www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Having "in" for arrays

reply Fra Mecca <me francescomecca.eu> writes:
Why doesn't D have a in keyword for arrays?

The docs explains that you can use in only for associative arrays 
but I don't see the reasons for such decision.


Example code:

void main()
{
	auto v = ["r", "i", "o"];
	assert ("r" in v);
}


That currently fails:
main.d(4): Error: incompatible types for (("r") in (v)): 'string' 
and 'string[]'
Nov 22 2017
next sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
On Wednesday, November 22, 2017 08:03:50 Fra Mecca via Digitalmars-d-learn 
wrote:
 Why doesn't D have a in keyword for arrays?

 The docs explains that you can use in only for associative arrays
 but I don't see the reasons for such decision.


 Example code:

 void main()
 {
   auto v = ["r", "i", "o"];
   assert ("r" in v);
 }


 That currently fails:
 main.d(4): Error: incompatible types for (("r") in (v)): 'string'
 and 'string[]'
in is supposed to be at worst O(log n), whereas to do the operation for an array would be O(n). If you want to search for a specific element in an array than use std.algorithm.find or std.algorithm.canFind. - Jonathan M Davis
Nov 22 2017
prev sibling parent reply Dukc <ajieskola gmail.com> writes:
On Wednesday, 22 November 2017 at 08:03:50 UTC, Fra Mecca wrote:
 void main()
 {
 	auto v = ["r", "i", "o"];
 	assert ("r" in v);
 }
Also note that even if it wereimplemented, you search for 'r' instead of "r". "r" is a string, but you would want to search for a char.
Nov 22 2017
parent reply lobo <swamplobo gmail.com> writes:
On Wednesday, 22 November 2017 at 09:36:43 UTC, Dukc wrote:
 On Wednesday, 22 November 2017 at 08:03:50 UTC, Fra Mecca wrote:
 void main()
 {
 	auto v = ["r", "i", "o"];
 	assert ("r" in v);
 }
Also note that even if it wereimplemented, you search for 'r' instead of "r". "r" is a string, but you would want to search for a char.
Isn't 'v' an array of strings? If it were a array of chars, then the search would be 'r'. bye, lobo
Nov 22 2017
parent Dukc <ajieskola gmail.com> writes:
On Wednesday, 22 November 2017 at 10:32:48 UTC, lobo wrote:
 On Wednesday, 22 November 2017 at 09:36:43 UTC, Dukc wrote:
 On Wednesday, 22 November 2017 at 08:03:50 UTC, Fra Mecca 
 wrote:
 void main()
 {
 	auto v = ["r", "i", "o"];
 	assert ("r" in v);
 }
Also note that even if it wereimplemented, you search for 'r' instead of "r". "r" is a string, but you would want to search for a char.
Isn't 'v' an array of strings? If it were a array of chars, then the search would be 'r'. bye, lobo
Oops, you're correct. My bad.
Nov 22 2017