2
$\begingroup$

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)?

$\endgroup$

marked as duplicate by rm -rf Aug 27 '14 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.

6
$\begingroup$

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

$\endgroup$
  • 2
    $\begingroup$ 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) $\endgroup$ – rm -rf Aug 27 '14 at 18:23
3
$\begingroup$

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
$\endgroup$
  • $\begingroup$ Ah, so that's how you use Block. Thanks! $\endgroup$ – Raphael Aug 28 '14 at 9:43

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