开发者

How Two Iterate Over Two Arrays In A Strongly Typed Language?

I have had this question in many languages, but I never happened to pursue the question. I only googled the questions, but rarely got results.

I figured it out, but I just wanna make sure this is the best way to go.

Lets take an Example: (i'll make it as general as possible so that it hopefully works in every language.)

firstArray[0] = 1;
firstArray[1] = 2;
firstArray[2] = 3;

secondArray[0] = 'a';
secondArray[1] = 'b';
secondArray[2] = 'c';

Now lets imagine if both these arrays are endless.

If I wanted to get these results:

开发者_C百科
1a
2b
3c

Then can I write this?:

for (int i=0; i < 3; i++)
{
print(firstArray[i] + secondArray[i]);
}


Yes, you can do that as long as neither array is shorter than the range you're iterating and both contain types that can be added to each other with the + operator with or without casting.


The title of your questions says if this is possible in a strongly typed language. Here is what Wikipedia mentions about strong typing http://en.wikipedia.org/wiki/Strong_typing (check the example of concatenating strings and integers). If this is what you are asking then the answer is no. You cannot do this in strongly typed languages.

E.g. you cannot do this in Python (and I believe Python is strongly typed)



a = [1,2,3]
b = ['a','b','c']

for i in xrange(len(a)):
    print (a[i]+b[i])


You will have to typecast to a common compatible type for the operator.



a = [1,2,3]
b = ['a','b','c']

for i in xrange(len(a)):
    print (str(a[i]) + b[i])


This is not possible in C and C++ too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜