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.

This question already has an answer here:

Consider the following (pseudo-)function definition:

f[l_] := Let[{
          a = Length[l],
          b = First[l],
          c = b/a,
         }, c*10]

So for instance, f[{2,3,4,5}] should output 5.

Currently, I only know variants for Let that

  • set a, b and c globally (on the first call of f) or
  • don't allow the definition of c because a and b are not defined.

What is the most simple way to define local variables whose definitions may depend on each other (upwards)?

share|improve this question

marked as duplicate by rm -rf Aug 27 at 18:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

up vote 5 down vote accepted

If you have Version 10 use the function Where in the GeneralUtilities package like this:

Needs["GeneralUtilities`"]

f[l_] := Where[a = Length[l], b = First[l], c = b/a, c*10]

Then:

f[{2, 3, 4, 5}]

5

share|improve this answer
1  
I think it would be better to post this answer to the related main post so that it can be easily found (see link in question) –  rm -rf Aug 27 at 18:23

Why not just this?

f[l_] := Block[{a,b,c},
          a = Length[l];
          b = First[l];
          c = b/a;
          c*10]

Then

f[{2, 3, 4, 5}]
5
share|improve this answer
    
Ah, so that's how you use Block. Thanks! –  Raphael Aug 28 at 9:43

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