Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

SCALA HELP: I need the total code at the end code up the following functions in Scala dealing with Vectors ( we will use these

SCALA HELP: I need the total code at the end

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Fundamentals Study Guide

Authors: Dr. Sergio Pisano

1st Edition

B09K1WW84J, 979-8985115307

More Books

Students also viewed these Databases questions