4
$\begingroup$

I am struggling with levels and #, if I understand this I think I will be able to grasp the entire concept.

 Apply[#1 &, {envelope[1, order["sku1", 5, 10, 4.98]], 
  envelope[2, order["sku2", 3, 67, 98]]}, {1}]
{1,2}

This makes perfect sense.

Keeping everything els equal but changing the slot to #2:

{order["sku1", 5, 10, 4.98], order["sku2", 3, 67, 98]}

This makes also perfect scence.

Then I am going back to #1 but now at level 2

{envelope[1, "sku1"], envelope[2, "sku2"]}

Why do I get this output I was only expecting Sku1 and Sku2.

I also wonder why Depth in this case equals 4, but if I put level 3 I get the entire list?

I know this is very simple but I have been struggling with seeing the logic.

I have spent quite a lot of time trying to grasp this so please try make it as clear as possible. And If you do not understand the question or think it is poorly explained give me a comment before downgrading the question.

$\endgroup$
2
  • $\begingroup$ Duplicate of "Levels: How do they work?" $\endgroup$
    – rm -rf
    Sep 25, 2013 at 1:17
  • $\begingroup$ @rm-rf I think it is closely related. Although convolved, OP's problem seems to more about Apply than the Levels which is well answered by Murta. $\endgroup$
    – Kuba
    Sep 25, 2013 at 6:17

1 Answer 1

4
$\begingroup$

It's easier to understand using Map. Using:

list ={envelope[1,order["sku1",5,10,4.98]],envelope[2,order["sku2",3,67,98]]}

if you do Map[f,list,{2}], you get:

{envelope[f[1],f[order[sku1,5,10,4.98]]],envelope[f[2],f[order[sku2,3,67,98]]]}

The trick here is that Apply when used in an Atom is the Atom itself.

f @@ 1

1

So with Apply[# &, list, {2}] you get:

{envelope[1,sku1],envelope[2,sku2]}

Levels are nicely visualized using TreeForm:

enter image description here

This post has a much more deeper and illustrative Level explanation.

$\endgroup$
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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