Page 1 of 1

Make a sum in thyme

PostPosted: Tue Oct 06, 2009 3:20 pm
by KarateBrot
for(n, (i)=>{ . . . })
How can I make a sum with the for-function?

for examlpe this simple sum
Image

I'm asking you because for example if I type "for(10, (i)=>{i})" it just shows the 10th member:
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 => it just shows the 10th member (the 9) as a result but not the whole sum.

So again... How can I make a sum with the for-function?

Thanks :thumbup:

- - - - -

I just found out how it works. If anyone needs it, here's the thyme code:

Code: Select all
scene.my.sum = (n) =>
{
   value := 0;
   for(n, (i)=>{value = value + i});
   value
}


For example:
scene.my.sum(6) = 15 (because of 0 + 1 + 2 + 3 + 4 + 5)

I will extend this idea to make a general sum function so you can add everything you want.

Re: Make a sum in thyme

PostPosted: Wed Oct 07, 2009 3:16 am
by immibis
To add the values in an array, use this (based on your code just now):
Code: Select all
scene.my.sum = (length, array) =>
{
    value := 0
    for(length, (i)=>{value = value + array(i)})
    value
}


To add consecutive numbers from 0, I suggest you use this:
Code: Select all
scene.my.sum = (n) => {(n)*(n-1)/2.0}

Re: Make a sum in thyme

PostPosted: Thu Oct 08, 2009 10:21 pm
by KarateBrot
thanks for your reply :thumbup:

i've got one question: what is the bracket of array[i] for? i only know array(i)

- - - - -

Code: Select all
scene.my.sum = (n) => {(n)*(n-1)/2.0}

i know this formula but i just wanted to give an example so i don't want to only calculate 1+2+3+4+...+n ;)

Re: Make a sum in thyme

PostPosted: Fri Oct 09, 2009 1:18 am
by immibis
Sorry, that should be array(i). I've edited my post.