If algorithms can be converted into code of any language, what is the point in having multiple languages?

955 viewsOtherTechnology

If algorithms can be converted into code of any language, what is the point in having multiple languages?

In: Technology

21 Answers

Anonymous 0 Comments

Here is a way to sort elements using a merge sort in two different languages. I think it will illustrate the point well. Some language are better at some things than others. Some languages excel at more abstract mathematical problem solving, others are very good at working with memory and interfacing with hardware. Haskel can make a more compact sort, C takes several more lines to do it.

**Haskell:**
“`
mergeSort :: (Ord a) => [a] -> [a]
mergeSort [] = []
mergeSort [a] = [a]
mergeSort a =
merge (mergeSort firstFew) (mergeSort lastFew)
where firstFew = take ((length a) `div` 2) a
lastFew = drop ((length a) `div` 2) a
— Expects a and b to already be sorted
merge :: (Ord a) => [a] -> [a] -> [a]
merge a [] = a
merge [] b = b
merge (a:as) (b:bs)
| a < b = a:(merge as (b:bs))
| otherwise = b:(merge (a:as) bs)
“`

**and C:**
“`
void TopDownMergeSort(A[], B[], n)
{
CopyArray(A, 0, n, B); // one time copy of A[] to B[]
TopDownSplitMerge(A, 0, n, B); // sort data from B[] into A[]
}

void TopDownSplitMerge(B[], iBegin, iEnd, A[])
{
if (iEnd – iBegin <= 1) // if run size == 1
return; // consider it sorted
iMiddle = (iEnd + iBegin) / 2; // iMiddle = mid point
TopDownSplitMerge(A, iBegin, iMiddle, B); // sort the left run
TopDownSplitMerge(A, iMiddle, iEnd, B); // sort the right run
TopDownMerge(B, iBegin, iMiddle, iEnd, A);
}

void TopDownMerge(B[], iBegin, iMiddle, iEnd, A[])
{
i = iBegin, j = iMiddle;

for (k = iBegin; k < iEnd; k++) {
if (i < iMiddle && (j >= iEnd || A[i] <= A[j])) {
B[k] = A[i];
i = i + 1;
} else {
B[k] = A[j];
j = j + 1;
}
}
}

void CopyArray(A[], iBegin, iEnd, B[])
{
for (k = iBegin; k < iEnd; k++)
B[k] = A[k];
}
“`

You are viewing 1 out of 21 answers, click here to view all answers.