Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

"Lazy" mapping with Or & And?

10 views
Skip to first unread message

David Bevan

unread,
Sep 29, 2011, 2:10:29 AM9/29/11
to

Although Or[f[x1],f[x2],f[x3],...] only evaluates the f[xi] up to the first that returns True, Or @@ f /@ [x1,x2,x3,...] doesn't.

To optimise Or when mapping like this, I've been using mapOrF below. Is the re a better or more preferred solution? Can Hold help?

mapOrF0[f_,s_]:=Or@@f/@s
mapAndF0[f_,s_]:=And@@f/@s

mapOrF[f_,s_]:=TrueQ@Scan[If[f[#],Return[True]]&,s]
mapAndF[f_,s_]:=If[Scan[If[!f[#],Return[False]]&,s],,False,True]

list=Range[1000000];
mapOrF0[#>0&,list]//Timing
mapOrF[#>0&,list]//Timing

{1.297,True}
{0.095,True}

Thanks.

David Bevan
David...@pb.com

Ray Koopman

unread,
Sep 30, 2011, 4:05:49 AM9/30/11
to

Leonid Shifrin

unread,
Sep 30, 2011, 4:08:54 AM9/30/11
to
Hi David,

I have used a very similar construct, which differs from yours in that the
scanned function holds its argument, so that this becomes a true macro. The code and some discussion lives here:

http://stackoverflow.com/questions/4911827/non-standard-evaluation-and-packedarray/4913107#4913107

along with a different (alternative) version with a different syntax, which
I implemented using exceptions with Module - localized tags.

Cheers,
Leonid

On Thu, Sep 29, 2011 at 10:05 AM, David Bevan <david...@pb.com> wrote:

>
> Although Or[f[x1],f[x2],f[x3],...] only evaluates the f[xi] up to the first
> that returns True, Or @@ f /@ [x1,x2,x3,...] doesn't.
>
> To optimise Or when mapping like this, I've been using mapOrF below. Is the
> re a better or more preferred solution? Can Hold help?
>
> mapOrF0[f_,s_]:=Or@@f/@s
> mapAndF0[f_,s_]:=And@@f/@s
>
> mapOrF[f_,s_]:=TrueQ@Scan[If[f[#],Return[True]]&,s]
> mapAndF[f_,s_]:=If[Scan[If[!f[#],Return[False]]&,s],,False,True]
>
> list=Range[1000000];
> mapOrF0[#>0&,list]//Timing
> mapOrF[#>0&,list]//Timing
>
> {1.297,True}
> {0.095,True}
>
> Thanks.
>
> David Bevan
> David...@pb.com
>
>
0 new messages