Simulate the length function to get the list length

I am trying to simulate the Length function in Mathematica v.8 to get the length of a list. Given these facts:

  • An empty list is represented as {}
  • l = Rest [l] assigns l (which is a list) a list l without the first element
  • while loop

This is my first year using math, and I'm not too good at it, so maybe something (or all) is wrong with what I'm doing:

Ej1[l_List] := Module[{i, v},
v = {{}};
i = 1;
While[l != v, l = Rest[l]; i++]
Return[i]
]

l = {a, b, c, d, e};

When I try to run it, the loop never ends and it gives me the following warnings:

Set::shape: Lists {a,b,c,d,e} and {b,c,d,e} are not the same shape. >>

Set::shape: Lists {a,b,c,d,e} and {b,c,d,e} are not the same shape. >>

Set::shape: Lists {a,b,c,d,e} and {b,c,d,e} are not the same shape. >>

General::stop: Further output of Set::shape will be suppressed during this calculation. >>
+5
source share
6 answers

, l, , .

Ej1[l_List] := Module[{i = 0, v = {}, thisl},
  thisl = l;
  While[thisl != v, thisl = Rest[thisl]; i++];
  i]
+9

NestWhile:

Clear[f];
f[l_List] := NestWhile[{Rest[#[[1]]], (#[[2]]) + 1} &, {l, 0}, 
   (#[[1]] != {}) &][[2]]

$RecursionLimit $IterationLimit, . , , . - -

f2[l_List] := Fold[(# + 1) &, 0, l]

:

list=RandomReal[1,10000];
Timing[f[list]]
(* ==> {3.35747, 10000} *)

Timing[f2[list]]
(* ==> {0.000658, 10000} *)
+6
length[myList_List] := Module[{x = 0}, Scan[x++ &, myList]; x]

length[{a, b, c, d, e, f, g}]

==> 7
+4

, If[]:

ClearAll[f];

f[l_List, i_: 0] := If[l != {}, f[Rest[l], i + 1], i];

f[{1,2}]
(*
-> 2
*)
+3

, , :

myLength[{}] := 0
myLength[lis_List] := 1 + myLength[Rest[lis]]

In[47]:= myLength[{}]
Out[47]= 0

In[48]:= myLength[{1}]
Out[48]= 1

In[49]:= myLength[{1,2,3,4,5}]
Out[49]= 5
+3

Same as Belisarius, but without explicit record If:

ClearAll[ej2];
ej2[lst_ /; (lst == {}), i_: 0] := i
ej2[lst_, i_: 0] := ej2[Rest[lst], i + 1]

ej2[{1, 2, 3, 4, 5}]
(*
5
*)
+1
source

All Articles