# Pure function on pure function

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]

• possible duplicate: 279200
– Kuba
Commented Feb 14, 2023 at 10:00
• With[{x=#},SelectFirst[t1,#>x&]]&/@t2 Commented Feb 14, 2023 at 11:24
• Commented Feb 14, 2023 at 11:32
• 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]} Commented Feb 14, 2023 at 15:30
• @flinty Possibly of interest: Why does the documentation call functions "pure"? Commented Apr 2 at 14:02

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
]

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

Just another way to do this using GroupBy and Lookup:

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

(*{2, 8, 16}*)

a = {2, 4, 8, 16};

b = {1, 5, 9};


Using FirstCase

FirstCase[a, x_ /; x > #] & /@ b


{2, 8, 16}

This is one way:

Map[max |-> SelectFirst[t1, # > max &], t2]


and another way as three separate functional operations:

t2 //
Map[GreaterThan/*SelectFirst] //
OperatorApplied[Construct][t1] //
Through


If you have version 14, Comap can be used too:

Comap[Map[GreaterThan/*SelectFirst, t2], t1]


Using nested queries:

Query[Query[All, GreaterThan/*SelectFirst][t2]][t1]