模拟 Length 函数来获取列表的长度
我正在尝试模拟 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]
]
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. >>
I'm trying to simulate the Length function in Mathematica v.8 to get the length of a list. Given this facts:
- Empty list is represented as {}
- l = Rest[l] assigns to l (which is a list) the list l without the first element
- a While loop
It's my first year using mathematica and I'm not too good at this so there's probably something (or everything) 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 this 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. >>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
主要问题是您试图修改输入变量
l
,这是不可能的,并且缺少分号。The main problems were that you were trying to modify the input variable,
l
, which is not possible, and you had a missing semi-colon.您还可以使用
NestWhile
:此代码不受
$RecursionLimit
或$IterationLimit
限制,因此它也适用于非常大的列表。缺点是它效率不高,因为在每个迭代步骤中都会对剩余列表进行复制。计算列表中元素的更快方法是执行类似比较的操作:
You can also use
NestWhile
:This code isn't bounded by
$RecursionLimit
or$IterationLimit
so it also works for very large lists. The downside is that it isn't very efficient since in every iteration step a copy is made of the remaining list. A faster way of counting elements in a list is to do something likeAs a comparison:
递归地,使用
If[]
:Recursively, using
If[]
:这是另一个递归解决方案,我认为这是相当惯用的函数式编程:
Here is yet another recursive solution, in what I would argue is fairly idiomatic functional programming:
与贝利萨留相同,但没有显式编写
If
:Same as belisarius but without explicitly writing
If
: