วันศุกร์ที่ 21 ธันวาคม พ.ศ. 2550

Infinite Sequence Part I - Introduction

Sequence includes finite sequence and infinite sequence. Finite sequence is a set. There are many classes in .NET that represent set such as Array, List, & Collection. With classes, you can reuse its functionality. Such as you want to find whether an object is in a list you can write:

bool exists = list.Contains(obj);

Or if you want to enumerate for first 10 objects:

var newList = list.Take(10);

Infinite sequence is infinity-members of list. Basic sample of infinite sequence is Natural numbers (1,2,3,...), Odd numbers (1,3,5,...), & Even numbers (2,4,6,...). But how can you represent infinite sequence into class? Such as if I want to find whether is 4 in Odd numbers, can I write?:

bool exists = oddNumbers.Contains(4);
//false

Or take first 10 numbers in Odd sequence:

var tenOdd = oddNumbers.Take(10);
//{1,3,5,7,9,11,13,15,17,19}

Most of the time, if you deal with above questions, you may rather write:

bool isOdd = 4 % 2 == 1

and

for (int i = 1; i <= 19; i += 2)

That means you have to know functionality of the sequence in order to use it. And you have to rewrite the function everytime. Odd and Even numbers are simple. How about Fibonacci and Prime sequence? Their incremental is not linear. And to check members in the list is more complex.

Is it easier if we can check a number prime list the same as we check in simple List?

var isPrime = prime.Contains(34567);

And get the first 1000 Fibonacci value without having to write codes to generate Fibonacci value everytime.

var milFib = fib.Take(1000);

How can you represent infinite sequence into class?
Continue next post :)

ไม่มีความคิดเห็น: