How to resolve the algorithm Dot product step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Dot product step by step in the Scala programming language

Table of Contents

Problem Statement

Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length.

As an example, compute the dot product of the vectors:

If implementing the dot product of two vectors directly:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Dot product step by step in the Scala programming language

Source code in the scala programming language

class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {
  import n._ // import * operator
  def dot(v2: Seq[T]) = {
    require(v1.size == v2.size)
    (v1 zip v2).map{ Function.tupled(_ * _)}.sum
  }
}

object Main extends App {
  implicit def toDot[T: Numeric](v1: Seq[T]) = new Dot(v1)

  val v1 = List(1, 3, -5)
  val v2 = List(4, -2, -1)
  println(v1 dot v2)
}

  

You may also check:How to resolve the algorithm Conditional structures step by step in the Make programming language
You may also check:How to resolve the algorithm Hash from two arrays step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Terminal control/Ringing the terminal bell step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Interactive programming (repl) step by step in the K programming language
You may also check:How to resolve the algorithm Pascal matrix generation step by step in the Haskell programming language