[Issue 5491] filter cannot be used in a function?
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Wed Jan 26 11:39:46 PST 2011
http://d.puremagic.com/issues/show_bug.cgi?id=5491
bearophile_hugs at eml.cc changed:
What |Removed |Added
----------------------------------------------------------------------------
CC| |bearophile_hugs at eml.cc
--- Comment #5 from bearophile_hugs at eml.cc 2011-01-26 11:37:32 PST ---
(In reply to comment #0)
> import std.algorithm, std.conv, std.stdio;
>
> enum UsbDevType: uint { indifferent = 0, parent_of_checked = 1, hub_dub_7 =
> 0x2001f103, spider_hub = 0x05e30608, gateway = 0x11A03232 }
> struct UsbDevice { //{{{
> UsbDevType dev_type;
> // not essential here ...
> string toString(){ return to!string( dev_type ); }
> }
>
> UsbDevice [] gateways_only( UsbDevice []devices ){ return filter!("a.dev_type
> == UsbDevType.gateway" )( devices ); }
This works:
auto gateways_only(UsbDevice[] devices) {
return filter!((a){ return a.dev_type == UsbDevType.gateway; })(devices);
}(In reply to comment #0)
> The following code:
> _______________________________________________________________________________
> import std.algorithm, std.conv, std.stdio;
>
> enum UsbDevType: uint { indifferent = 0, parent_of_checked = 1, hub_dub_7 =
> 0x2001f103, spider_hub = 0x05e30608, gateway = 0x11A03232 }
> struct UsbDevice { //{{{
> UsbDevType dev_type;
> // not essential here ...
> string toString(){ return to!string( dev_type ); }
> }
>
> UsbDevice [] gateways_only( UsbDevice []devices ){ return filter!("a.dev_type
> == UsbDevType.gateway" )( devices ); }
>
> unittest{
> auto devices = [ UsbDevice( UsbDevType.gateway ), UsbDevice(
> UsbDevType.indifferent ), UsbDevice( UsbDevType.hub_dub_7 ) ];
> auto gateways = gateways_only( devices );
> foreach( UsbDevice dev; gateways ) writeln( dev.toString() );
> }
The formatting of your code is very bad.
This works:
import std.algorithm, std.conv, std.stdio;
enum UsbDevType: uint {
indifferent = 0,
parent_of_checked = 1,
hub_dub_7 = 0x2001f103,
spider_hub = 0x05e30608,
gateway = 0x11A03232
}
struct UsbDevice {
UsbDevType dev_type;
string toString() {
return to!string(dev_type);
}
}
auto gateways_only(UsbDevice[] devices) {
return filter!((a){ return a.dev_type == UsbDevType.gateway; })(devices);
}
void main() {
auto devices = [UsbDevice(UsbDevType.gateway),
UsbDevice(UsbDevType.indifferent),
UsbDevice( UsbDevType.hub_dub_7)];
auto gateways = gateways_only(devices);
foreach (UsbDevice dev; gateways)
writeln(dev.toString());
}
Currently string-defined functions that you give to filter, map, etc, can't use
symbol names defined elsewhere, like UsbDevType. So you need to use a lambda
template, as I have done here, or a proper delegate.
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list