2
$\begingroup$

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$
0

2 Answers 2

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

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