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.

I have the following working expression:

In[15]:= Length[Select[IntegerPartitions[10],First[#1]==5&]]
Out[15]= 7

But, instead of using the constant 5 I want to map all values from 1 to 10 into this function. If I nest the pure function inside another it doesn't work:

In[18]:= Map[Length[Select[IntegerPartitions[10],First[#]==#&]]&,Range[10]]
Out[18]= {0,0,0,0,0,0,0,0,0,0}

What is the way to do this?

share|improve this question
    
You may need to use the variant form Map[Function[{x},...,First[#]==x&]]],...]. –  Daniel Lichtblau Dec 6 '13 at 22:29
2  
This variant seems to work. Map[ With[{a = #}, Length[Select[IntegerPartitions[10], First[#] == a &]]] &, Range[10]] Out[257]= {1, 5, 8, 9, 7, 5, 3, 2, 1, 1} –  Daniel Lichtblau Dec 6 '13 at 22:31
2  
The name is not virtual function but Pure Function in a Mathematica context. –  Sjoerd C. de Vries Dec 6 '13 at 23:41
1  
Possibly duplicate (16947). –  Silvia Dec 7 '13 at 4:26

3 Answers 3

up vote 2 down vote accepted

You can have a pure function inside a pure function even in this case, you just can't have the name of the parameter being "#" in both. This works:

Map[Function[x, 
  Length[Select[IntegerPartitions[10], First[#] == x &]]], Range[10]]
share|improve this answer

This is probably not going to be the best answer but offering it as an opener or as a guide to towards a better solution

Setting your initial input as a function

f[n_]:=Length[Select[IntegerPartitions[10],First[#]==n&]]

then

Map[f,Range[10]]
{1, 5, 8, 9, 7, 5, 3, 2, 1, 1}

No doubt regular contributors can improve on this

share|improve this answer

You can also perform this without "netsted functions" issue. For example:

Count[IntegerPartitions[10][[All, 1]], #] & /@ Range[10]

It could be even faster but we have to assume that you know the output of IntegerPartitions (explained on the bottom):

Reverse @ Tally[IntegerPartitions[10][[All, 1]]][[All, 2]]

Description

  • IntegerPartitions[10][[All, 1]] because only first elements are important

  • [[All, 2]] after Tally -> here we assume that we know that there will be a set of values from 1 to 10, otherwise some sort of filtering is needed.

  • Reverse because IntegerPartitions list values are decreasing.

share|improve this answer

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.