7
$\begingroup$

Given

t1 = {2, 4, 8, 16};
t2 = {1, 5, 9};
First[Select[t1, # > 1 &]]     
First[Select[t1, # > 5 &]]
First[Select[t1, # > 9 &]]

can somehow be summarized by

 Table[First[Select[t1, # > x &]], {x, t2}]

to get the correct result

{2, 8, 16}

Is there a way to use two pure functions connected instead of working around the problem by using Table? Something like (which does not work!):

First[Select[t1, # > # &] & /@ t2]
$\endgroup$
4
  • $\begingroup$ possible duplicate: 279200 $\endgroup$
    – Kuba
    Feb 14 at 10:00
  • 2
    $\begingroup$ With[{x=#},SelectFirst[t1,#>x&]]&/@t2 $\endgroup$
    – chyanog
    Feb 14 at 11:24
  • 1
    $\begingroup$ Related Pure function inside another pure function $\endgroup$
    – user1066
    Feb 14 at 11:32
  • 3
    $\begingroup$ We should really call these anonymous functions when using slots #, because technically pure functions are not supposed to affect mutable state or produce different values given identical arguments, but Mathematica's 'pure' functions can do this, e.g: x = 1; f = (++x; x + #) &; {f[1],f[1],f[1]} $\endgroup$
    – flinty
    Feb 14 at 15:30

2 Answers 2

11
$\begingroup$

Here are 2 suggestions:

First @ Select[t1, GreaterThan[#]] & /@ t2
Function[x, First @ Select[t1, # > x &]] /@ t2

Edit

Or, if you want to go really abstract:

Map[
 First@Select[t1,
    OperatorApplied[Function[#1 > #2]][#1]
    ] &,
 t2
 ]
$\endgroup$
5
  • 7
    $\begingroup$ SelectFirst[t1, GreaterThan[#]] & /@ t2 but at some point Function is the way to go anyway. $\endgroup$
    – Kuba
    Feb 14 at 9:59
  • $\begingroup$ Using |-> syntax you can avoid Function e.g: (x |-> SelectFirst[t1, # > x &]) /@ t2 $\endgroup$
    – flinty
    Feb 14 at 15:37
  • 3
    $\begingroup$ Look Ma, no Slots: Through[(SelectFirst /@ GreaterThan /@ t2) @ t1] :p $\endgroup$
    – Kuba
    Feb 15 at 7:28
  • $\begingroup$ @flinty What does |-> stand for? I use Mathematica 12.1 and I get an error. $\endgroup$
    – user57467
    Feb 16 at 12:18
  • 1
    $\begingroup$ @user57467 It was added in 12.2 as a short hand for Function, so one can do things like x|->x^2. $\endgroup$
    – flinty
    Feb 16 at 12:28
5
$\begingroup$

Just another way to do this using GroupBy and Lookup:

Lookup[GroupBy[t1, GreaterThan[#], First] & /@ t2, True]

(*{2, 8, 16}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.