D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 9740 - strange interaction between map and filter
Summary: strange interaction between map and filter
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: x86 All
: P2 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-03-17 01:16 UTC by Knud
Modified: 2019-08-09 06:43 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Knud 2013-03-17 01:16:24 UTC
#!/usr/bin/rdmd
import std.stdio;
import std.algorithm;

void main()
{

 bool[][][] clist=[[[true, true], [false, true]],[[true, false], [true, true]],[[false, true], [true, true]]];

 auto x=0;
writeln(clist);

auto fpos=delegate bool(bool[][] a){return(a[x]!=[true,false]);};
auto fneg=delegate bool(bool[][] a){return(a[x]!=[false,true]);};

 writeln("neg:",map!(delegate (bool[][] a){a[x][1]=true; return a;})(filter!(fneg)(clist)));   
 writeln("pos:",map!(delegate (bool[][] a){a[x][0]=true; return a;})(filter!(fpos)(clist)));    
 
}

outputs: 
[[[true, true], [false, true]], [[true, false], [true, true]], [[false, true], [true, true]]]
neg:[[[true, true], [false, true]], [[true, true], [true, true]]]
pos:[[[true, true], [false, true]], [[true, true], [true, true]], [[true, true], [true, true]]]

if you change the order of the writeln you get:[[[true, true], [false, true]], [[true, false], [true, true]], [[false, true], [true, true]]]
pos:[[[true, true], [false, true]], [[true, true], [true, true]]]
neg:[[[true, true], [false, true]], [[true, true], [true, true]], [[true, true], [true, true]]]
Comment 1 Maxim Fomin 2013-03-17 01:39:12 UTC
What exactly is wrong?

Removed OS specific since same happens on windows.
Comment 2 Knud 2013-03-17 01:46:20 UTC
(In reply to comment #1)
> What exactly is wrong?
The second filter don't work, but it should.

> 
> Removed OS specific since same happens on windows.
Comment 3 Simen Kjaeraas 2019-08-09 06:43:20 UTC
The map function changes the contents of the array, and unsurprisingly, that changes what the filter filters. This is not a bug in filter and map, but in your code.

Reduced example:

    auto arr = [[false]];
    
    writeln(arr.filter!(a =>  a[0]).map!(a => a[0] = true)); // []
    writeln(arr.filter!(a => !a[0]).map!(a => a[0] = true)); // [true]
    writeln(arr.filter!(a =>  a[0]).map!(a => a[0] = true)); // [false]

This is possibly caused by a misguided idea that the array is a value type.