HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftModerate

Dot product, ported from C to Swift

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
swiftproductdotfromported

Problem

This is how I posted a method from C to Swift. I tested it well, it seems to work. It's there a way to write this better, following good practices of Swift? The original is in C and the target must be in Swift.

Original C Code:

inline float mac(const float *a, const float *b, unsigned int size)
{
    float sum = 0;
    unsigned int i;

    for (i = 0; i < size; i++)
        sum += (*a++) * (*b++);
    return sum;
}


and the translation to Swift:

func mac(a : [Float], b : [Float], size : Int) -> Float
{
    var sum : Float = 0;

    for (var i = 0; i < size; i++){
        sum += (a[i]) * (b[i]);
    }
return sum;
}

Solution

You can remove the size parameter as arrays know their own size in Swift, and use the zip, map and reduce functions to perform the computation rather than the C-style for loop, which is now unavailable in the latest versions of Swift (as is i++):

func mac(a: [Float], b: [Float]) -> Float {
    return zip(a, b).map(*).reduce(0, +)
}


  • The zip function takes two arrays and makes a single array of tuples, with each tuple containing the nth element from each array.



  • The map function changes each element of the array with a user-supplied function. In this case, the multiplication operator is passed in, which multiplies each pair.



  • The reduce function performs the task of summing each result (starting at 0).

Code Snippets

func mac(a: [Float], b: [Float]) -> Float {
    return zip(a, b).map(*).reduce(0, +)
}

Context

StackExchange Code Review Q#119301, answer score: 16

Revisions (0)

No revisions yet.