Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
3  
Something like : Function[{x, y}, Select[x, # == y &]][thelist, "this"] ? –  b.gatessucks Jul 21 '12 at 19:11
add comment

3 Answers 3

up vote 4 down vote accepted

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"} *)
share|improve this answer
    
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
add comment

This is normally done with DownValues definitions:

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

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

sel[thelist, "this"]
{"this"}
share|improve this answer
    
Well, ... very true. I guess I was too much into a certain style of coding. –  NikolajK Jul 21 '12 at 23:19
add comment

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"]
share|improve this answer
2  
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. –  rm -rf 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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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