2

Simulate length function to get the length of a list

 3 years ago
source link: https://www.codesd.com/item/simulate-length-function-to-get-the-length-of-a-list.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Simulate length function to get the length of a list

advertisements

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. >>


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.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK