模拟长度函数以获取列表的长度

Car*_*los 5 wolfram-mathematica function list

我正在尝试在Mathematica v.8中模拟Length函数来获取列表的长度.鉴于这一事实:

  • 空列表表示为{}
  • l = Rest [l]为没有第一个元素的列表l分配l(这是一个列表)
  • 一个while循环

这是我使用mathematica的第一年,我对此并不太擅长,所以我正在做的事情可能有些事情(或者一切都有问题):

Ej1[l_List] := Module[{i, v},
v = {{}};
i = 1;
While[l != v, l = Rest[l]; i++]
Return[i]
]
Run Code Online (Sandbox Code Playgroud)

L = {A,B,C,d,E};

当我尝试运行它时,循环永远不会结束,它会给我这个警告:

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. >>
Run Code Online (Sandbox Code Playgroud)

Chr*_*nen 9

主要的问题是你试图修改输入变量l,这是不可能的,你有一个缺少的分号.

Ej1[l_List] := Module[{i = 0, v = {}, thisl},
  thisl = l;
  While[thisl != v, thisl = Rest[thisl]; i++];
  i]
Run Code Online (Sandbox Code Playgroud)


Hei*_*ike 6

您还可以使用NestWhile:

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

这个代码不被约束$RecursionLimit$IterationLimit因此它也适用于非常大名单.缺点是效率不高,因为在每个迭代步骤中都会复制剩余的列表.计算列表中元素的更快方法是执行类似的操作

f2[l_List] := Fold[(# + 1) &, 0, l]
Run Code Online (Sandbox Code Playgroud)

作为比较:

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

Timing[f2[list]]
(* ==> {0.000658, 10000} *)
Run Code Online (Sandbox Code Playgroud)