1
$\begingroup$

I want to create a new function nLength that applies Lengthin each element from a list automatically. For example:

I have a list: {1,{2,3},{4,5,6}}

If I use nLengthhas to return:

nLength[{1,{2,3},{4,5,6}}]

{1,2,3}

Which is the number of elements in each element.

I have tried some like that, but doesn't works:

nLength[{n__}] := Map[Length, #]&n
$\endgroup$
12
  • 2
    $\begingroup$ Possible duplicate of How to apply `Length` in all elements $\endgroup$ Commented Jan 22, 2019 at 18:50
  • 1
    $\begingroup$ Is not the same question. Now I want to create a new function using a pure function. Some in syntax (I guess) is wrong and I don't know where. $\endgroup$
    – Mateus
    Commented Jan 22, 2019 at 18:55
  • 4
    $\begingroup$ nLength[{n__}] := Map[Length[#] &, {n}] is what you're looking for. By the way the first element is not a list, so it's length is 0. $\endgroup$
    – QuantumDot
    Commented Jan 22, 2019 at 19:13
  • 2
    $\begingroup$ Wouldn't it be clearer and fewer keystrokes to avoid defining a new function and use Length/@{1, {1, 2}, {1, 2, 3}} since all the function does is call the built-in Length function? $\endgroup$
    – MassDefect
    Commented Jan 22, 2019 at 19:29
  • 2
    $\begingroup$ Why is Length[1] == 1? $\endgroup$
    – Kuba
    Commented Jan 22, 2019 at 19:53

2 Answers 2

2
$\begingroup$

I can think of no good reason for using a pure function in the implementation of your variant of List, but I do think your requirement that atoms should be treated as having length 1 is something that requires some thought.

Here is how I would do it.

Clear[helper, nLen]
helper[item_?AtomQ] := 1
helper[item_] := Length[item]
nLen[u_ /; Length[u] === 0] := 0
nLen[u_] := helper /@ u

Now some tests including looking at some edge cases.

nLen[{1, {2, 3}, {4, 5, 6}}]

{1, 2, 3}

nLen[foo[{}, {1}, bar[2, 3], quux[4, {a, b}, {}]]]

foo[0, 1, 2, 3]

nLen[{}]

0

nLen[f[]]

0

Note that like Length, nLen works on expression with any head.

$\endgroup$
1
$\begingroup$
ClearAll[lENGTH]
lENGTH = Module[{s = 0}, ++s & /@ Map[List, Inactivate @ #, {-1}]; s] &;

Examples:

Grid[Prepend[{#, lENGTH@#, Length@#} & /@ {3, a, {}, {{}}, f[], a + b, a b c,
     f[1, aa, b, 3], {1, 2}, {1, 2, 3},{1, {2, {3, {4, {5}}}}},
     <|a -> 1, b -> 2|>, SparseArray[{{1, 1} -> 1, {10, 3} -> 2}], Rational[x, 3], y^4}, 
    {"expr", "lENGTH @ expr", "Length @ expr"}], Dividers -> All]

enter image description here

$\endgroup$

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