Skip to content

Instantly share code, notes, and snippets.

@george-hawkins
Created October 23, 2016 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save george-hawkins/894231187c526b8ddc57d18201451689 to your computer and use it in GitHub Desktop.
Save george-hawkins/894231187c526b8ddc57d18201451689 to your computer and use it in GitHub Desktop.
package week2
object Lecture6 extends App {
def reduceSeg1[A](inp: Array[A], left: Int, right: Int, a0: A, f: (A, A) => A): A = {
var a = a0
var i = left
while (i < right) {
a = f(a, inp(i))
i += 1
}
a
}
def mapSeg[A,B](inp: Array[A], left: Int, right: Int, fi : (Int, A) => B, out: Array[B]): Unit = {
var i = left
while (i < right) {
out(i) = fi(i, inp(i))
i += 1
}
}
def scanLeft[A](inp: Array[A], a0: A, f: (A, A) => A, out: Array[A]): Unit = {
def fi(i: Int, an: A) = {
reduceSeg1(inp, 0, i, a0, f)
}
mapSeg(inp, 0, inp.length, fi, out)
val last = inp.length - 1
out(last + 1) = f(out(last), inp(last))
}
val inp = Array(1, 3, 8)
val out = new Array[Int](4)
scanLeft[Int](inp, 100, _+_, out)
println(out.toList)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment