Is there a way to call a function and have that function use an argument defined in an enclosing function?


set = Table@Range@50;

posE[set_] := Select[set, EvenQ]

tform1[mult_,set_] := (#*mult) & /@ set[[posE]];

t1set = tform1[10, set]

which leads to the following message/error,

Part::pspec: Part specification posE is neither an integer nor a list of integers. >>

I would like posE to get its argument set_ from the second argument in tform1 (also named set_).

Is this possible? is there a better way to do this?

(Note that I do not want to combine the two functions into a single function).

  • $\begingroup$ how about: Cases[set, x_?EvenQ :> 10 x]? (without knowing what you actually want to achieve) $\endgroup$ – Pinguin Dirk May 2 '13 at 7:59

You have defined a function posE[set] but when you call it, it has no argument. You must call it with an argument. So change the function definition to

 tform1[mult_,set_] := (#*mult) & /@ set[[posE[set]]];

If what you are really after is a list that goes from 20 to 500 by 20s (which is what this code seems to do) then there is much better way to do it.

Range[20, 500, 20]
  • $\begingroup$ No, I was just using these functions as an example. Thanks anyway. $\endgroup$ – geordie May 2 '13 at 7:57

is it too early to add an answer to my own question?

I just found a way to do it using With:

tform1[mult_, set_, pos_] := 
  With[{posf = pos[set]}, (#*mult) & /@ set[[posf]]];

t1set = tform1[10, set, posE]

This works very similar to @bill s' answer.

  • 1
    $\begingroup$ You could eliminate the With and just use tform1[mult_, set_, pos_] := (#*mult) & /@ set[[pos[set]]] as per Bill s answer. $\endgroup$ – image_doctor May 2 '13 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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