Curated collection of useful little scala functions that you can understand quickly.
View contents
View contents
Chunks an Vector into smaller Vector of specified size.
def chunk[T](xs: Vector[T], size: Int): Vector[Vector[T]] = {
if (xs.lengthCompare(size) <= 0) xs +: Vector()
else (xs take size) +: chunk(xs drop size, size)
}
Find first index of element in the Vector.
def indexOf[T](xs: Vector[T], el: T): Option[Int] = {
val indexes = for ((v, i) <- xs.zipWithIndex if v equals el) yield Some(i)
if(indexes.isEmpty) None else indexes.head
}
Calculates the greatest common denominator (gcd) of an Vector of numbers.
def gcd(numbers: Vector[Int]): Int = numbers reduce gcd
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
Calculates the lowest common multiple (lcm) of an array of numbers.
def lcm(numbers: Vector[Int]): Int = {
def lcm(a: Int, b: Int) = {
val g = gcd(a, b)
if (g == 0) 0 else a * b / g
}
numbers reduce lcm
}
Compute the bionomial coefficient
, n C k.
def binomialCoefficient(n: Int, k: Int): Int = {
if (k < 0 || k > n) return 0
if (k == 0 || k == n) return 1
val j = k min (n - k)
var c = 1
for (i <- 0 until j) c = c * (n - i) / (i + 1)
c
}
Converts InputStream to String.
def convertInputStreamToString(is: InputStream): String = Source.fromInputStream(is).mkString
Reads string from file.
def readFileAsString(file: File): String = Source.fromFile(file).getLines.mkString
This project is inspired by shekhargulati's little-java-functions, and his project is started as a Java fork of 30-seconds-of-code.
I'm planning to start implementing functions in little-java-functions project in Scala style. After that, I'll write my own functions. This project is just for my study and welcome PR and Issue for my bad implementation.