I would like to write this function in haskell
it is a union function with o(m+n) complexity
int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
printf(" %d ", arr1[i++]);
else if(arr2[j] < arr1[i])
printf(" %d ", arr2[j++]);
else
{
printf(" %d ", arr2[j++]);
i++;
}
}
/* Print remaining elements of the larger array */
while(i < m)
printf(" %d ", arr1[i++]);
while(j < n)
printf(" %d ", arr2[j++]);
}
The difference between programming languages is not just that different programming languages are different, but also that we use different programming languages differently. e.g. C and C++ are similar programming languages, but whereas C programs tend to allocate a few large blocks of memory, C++ programs tend to allocate more but smaller blocks of memory.
So: whereas your C function takes two arrays (and has to be passed their lengths explicitly), in Haskell we would use lists instead. (That’s not to say that Haskell programs never use arrays, just as it’s not true that C programs never use lists, just that C programs tend to use arrays and Haskell programs tend to use lists.)
Your C function calls
printf(), which both formats the output and sends it to stdout, but we’re going to those things separately.showSpacedworks with all values we can pass toshow.This
unionfunction requires only that the underlying elements can be compared. The two lists have to have the same type as each other. You’ll note that we’re using recursion instead of looping, and that by using lists instead of arrays we don’t have to keep track of array indices.We use pattern matching, both by giving three equations for
unionitself, and with thecaseexpression. Pattern matching is important in Haskell: find yourself a tutorial that explains it.And so in
printUnionwe put it all together. The list elements need to implementOrd(so we can callunion) andShow(so we can callshowSpaced), so they both appear in the type signature.As you’re coming from C, you may be worried about the efficiency of building up an intermediate list. Don’t be: the optimiser will fuse everything into a single loop.