Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Select any" in Mathematica

Does mathematica have something like "select any" that gets any element of a list that satisfies a criterion?

like image 713
nes1983 Avatar asked Jan 20 '26 04:01

nes1983


2 Answers

If you just want to return after the first matching element, use the optional third argument to Select, which is the maximum number of results to return. So you can just do

Any[list_List, crit_, default_:"no match"] := 
    With[{maybeMatch = Select[list, crit, 1]},
        If[maybeMatch =!= {},
            First[maybeMatch],
            default]

Mathematica lacks a great way to signal failure to find an answer, since it lacks multiple return values, or the equivalent of Haskell's Maybe type. My solution is to have a user-specifiable default value, so you can make sure you pass in something that's easily distinguishable from a valid answer.

like image 122
Pillsy Avatar answered Jan 23 '26 21:01

Pillsy


Well, the downside of Eric's answer is that it does execute OddQ on all elements of the list. My call is relatively costly, and it feels wrong to compute it too often. Also, the element of randomness is clearly unneeded, the first one is fine with me.

So, how about

SelectAny[list_List, criterion_] := 
 Catch[Scan[  If[criterion[#], Throw[#, "result"]] &, list]; 
  Throw["No such element"], "result"]

And then

SelectAny[{1, 2, 3, 4, 5}, OddQ]

returns 1.

I still wish something were built into Mathematica. Using home-brew functions kind of enlarges your program without bringing much direct benefit.

like image 30
nes1983 Avatar answered Jan 23 '26 21:01

nes1983



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!