2

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

Raphael
  • 559
  • 2
  • 12

2 Answers2

6

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

RunnyKine
  • 33,088
  • 3
  • 109
  • 176
  • 2
    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 '14 at 18:23
4

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
Öskå
  • 8,587
  • 4
  • 30
  • 49
rhermans
  • 36,518
  • 4
  • 57
  • 149