SML length function:
fun length(L) =
if (L=nil) then 0
else 1+length(tl(L));
For example:
length [1,2,3] = 3;
length [ [5], [4], [3], [2,1] ] = 4;
Based on the code, how do I change it if I also want to count the elements in the list of the list?
For example:
length [ [5], [4], [3], [2,1] ] = 5;
You could create another function that will use your function as follows:
fun d_length ( [] ) = 0
| d_length ( l :: l' ) = length(l) + d_length(l');
d_length[ [5], [4], [3], [2,1] ];
Or alternatively, use the build in reducer:
List.foldl (fn(e,a) => length(e) + a) 0 [ [5], [4], [3], [2,1] ];