# Function[] argument nesting for operations like Select[]

The following code selects a special element from a list

thelist = {"this", "notthis"};

Select[thelist, (# == "this") &]


What I want is a function which does just that and which takes lists (like thelist) and a string (like "this") as argument. However I have a problem, because Select already uses an abstract function and so the naive idea

sel:=Select[#1, (# == #2) &]

sel[thelist,"this"]


doesn't work. This is really about the Function command and the problem might not just appear with Select but any abstract function nesting.

How to construct the object I need?

-
Something like : Function[{x, y}, Select[x, # == y &]][thelist, "this"] ? – b.gatessucks Jul 21 '12 at 19:11

You could use With to assign your string to a named variable and modify it as:

With[{str = #2}, Select[#, # == str &]] &[thelist, "this"]
(* {"this"} *)


Another option is to use a formal symbol in the inner pure function and replace it with your actual string

Select[#, (# == \[FormalS]) & /. \[FormalS] -> #2] &[thelist, "this"]
(* {"this"} *)


Alternately, if you wanted to do it solely with pure functions, you could do something like what b.gatessucks mentioned in the comments.

Function[{x, y}, Select[x, # == y &]][thelist, "this"]
(* {"this"} *)

-
With is exactly what I was going to suggest, +1. :P – rcollyer Jul 21 '12 at 20:01
Thanks, not using # and doing it like username b.gatessucks said in the comment was sufficient. – NikolajK Jul 21 '12 at 22:55
As another possible permutation of the code: Select[#1, Function[test, test == #2]] &[thelist, "this"]. – J. M. Jul 22 '12 at 2:43

This is normally done with DownValues definitions:

thelist = {"this", "notthis"};

sel[L_List, S_String] := Select[L, (# == S) &]

sel[thelist, "this"]

{"this"}

-
Well, ... very true. I guess I was too much into a certain style of coding. – NikolajK Jul 21 '12 at 23:19

An alternative would be to use the Nearest[ ] function. This doesn't address the general issue, but does solve the specific question:

thelist = {"this", "notthis"};
Nearest[thelist, "this"]

-
thelist = {"cat", "but", "hit"}; Nearest[thelist, "fat"]... The example was just for illustration purposes, so merely addressing only the highly simplified case isn't very useful, IMO. – R. M. Jul 21 '12 at 21:19
user, I agree with R.M in this case, but nevertheless welcome to the site and thanks for contributing. – Mr.Wizard Jul 21 '12 at 23:40