Question: code up the following functions in Scala dealing with Vectors ( we will use these functions subsequently) v, w are vectors of type v: Vector[Double]

code up the following functions in Scala dealing with Vectors ( we will use these functions subsequently) v, w are vectors of type v: Vector[Double]

I will use an abbreviation for Vector[Double] as V, in code it looks as follows. That is, Scala lets you use a synonym for complicated ( but crucial ) types. So instead of writing v: Vector[Double] you can use the synonym and write v: V.

// initialization code here..

type V = Vector[Double]

mean(v: [V] ) , std(v: [V]), norm(v: [V]) where norm is the euclidean length of a vector

norm of v is often written as: |v|

dot(v: [V] ,w: [V]) where dot is the inner product of two vectors

add(v: [V] ,w:[V]) add two vectors element wise

subtract(v:[V],w: [V]) subtract w from v elementwise

scalarMult(x: Double, v: [V] ) multiply each vector element by the scalar x

scalarAdd(x: Double, v[V]) add the scalar x to each element ( could be used to subtract)

Hint: there are a couple of helpful functions built into Scala that you can use:

zip, map, and anonymous functions as the code snippets below demonstrate.

// This is from a Scala worksheet, like the REPL

println("Scala sample code") //> Scala sample code

type V = Vector[Double]

val v:V = Vector(1.0,2.0,3.0) //> v : main.scala.apps.scalaSampleCode.V = Vector(1.0, 2.0, 3.0)

val w:V = Vector(4.0,5.0,2.0) //> w : main.scala.apps.scalaSampleCode.V = Vector(4.0, 5.0, 2.0)

// add a scalar to each vector element

def scalarAdd(x: Double, v: V)={

v .map { element => x + element}

} //> scalarAdd: (x: Double, v: main.scala.apps.scalaSampleCode.V)scala.collection

//| .immutable.Vector[Double]

scalarAdd(13.0, v) //> res0: scala.collection.immutable.Vector[Double] = Vector(14.0, 15.0, 16.0)

// add two ectors , element by element

val zipped= v zip w //> zipped : scala.collection.immutable.Vector[(Double, Double)] = Vector((1.0,

//| 4.0), (2.0,5.0), (3.0,2.0))

val resultA = zipped.map {

pair => pair match { case(x,y) => x + y }

} //> resultA : scala.collection.immutable.Vector[Double] = Vector(5.0, 7.0, 5.0)

//|

resultA.sum //> res1: Double = 17.0

val resultConcise = zipped.map{ case(x,y) => x + y}.sum

//> resultConcise : Double = 17.0

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!