Find the "Recursive Size" of a List
Python, 42 bytes
f=lambda x:x*0==[]and len(x)+sum(map(f,x))
For a non-list, output 0. For a list, output its length plus the sum of the recursive outputs for its elements.
Lists fall above numbers and below strings in the Python 2 ordering, requiring []<=x<''
. Instead, we check x*0==[]
, whereas the result of 0
for a number or ''
for a string.
JavaScript (ES6), 39 37 bytes
Saved 2 bytes thanks to @edc65
f=a=>a.map&&a.map(x=>a-=~f(x),a=0)&&a
Jelly, 8 bytes
߀-ŒḊ?‘S
Try it online!
How it works
߀-ŒḊ?‘S Main link. Argument: x
ŒḊ? If x has non-zero depth:
߀ Recursively map the main link over its elements.
- Else, yield -1.
‘ Increment all integers in the result.
S Compute the sum of the result.
If x is an array, incrementing before adding is equivalent to computing
the sum of the elements and the length.
If x is an integer/character, incrementing -1 yields 0, as desired.