Scala Library: scala.util
scala.util
package util
Deprecated Value Members
object MurmurHash
An object designed to generate well-distributed non-cryptographic hashes. It is designed to hash a collection of integers; along with the integers to hash, it generates two magic streams of integers to increase the distribution of repetitive input sequences. Thus, three methods need to be called at each step (to start and to incorporate a new integer) to update the values. Only one method needs to be called to finalize the hash.
- Annotations
- @ deprecated
- Deprecated
- (Since version 2.10.0) Use the object MurmurHash3 instead.
- Source
Type Members
class DynamicVariable[T] extends AnyRef
DynamicVariables
provide a binding mechanism where the current value is found
through dynamic scope, but where access to the variable itself is resolved
through static scope.
The current value can be retrieved with the value method. New values should be
pushed using the withValue
method. Values pushed via withValue
only stay
valid while the withValue
‘s second argument, a parameterless closure,
executes. When the second argument finishes, the variable reverts to the
previous value.
someDynamicVariable.withValue(newValue) {
// ... code called in here that calls value ...
// ... will be given back the newValue ...
}
Each thread gets its own stack of bindings. When a new thread is created, the
DynamicVariable
gets a copy of the stack of bindings from the parent thread,
and from then on the bindings for the new thread are independent of those for
the original thread.
- Source
- Version
- 1.1, 2007-5-21
sealed abstract class Either[+A, +B] extends Product with Serializable
Represents a value of one of two possible types (a disjoint union.) Instances of Either are either an instance of scala.util.Left or scala.util.Right.
A common use of Either is as an alternative to scala.Option for dealing with possible missing values. In this usage, scala.None is replaced with a scala.util.Left which can contain useful information. scala.util.Right takes the place of scala.Some. Convention dictates that Left is used for failure and Right is used for success.
For example, you could use Either[String, Int]
to detect whether a received
input is a String or an Int.
val in = Console.readLine("Type Either a string or an Int: ")
val result: Either[String,Int] = try {
Right(in.toInt)
} catch {
case e: Exception =>
Left(in)
}
println( result match {
case Right(x) => "You passed me the Int: " + x + ", which I will increment. " + x + " + 1 = " + (x+1)
case Left(x) => "You passed me the String: " + x
})
A projection can be used to selectively operate on a value of type Either,
depending on whether it is of type Left or Right. For example, to transform an
Either using a function, in the case where it’s a Left, one can first apply the
left
projection and invoke map
on that projected Either. If a right
projection is applied to that Left, the original Left is returned, unmodified.
val l: Either[String, Int] = Left("flower")
val r: Either[String, Int] = Right(12)
l.left.map(_.size): Either[Int, Int] // Left(6)
r.left.map(_.size): Either[Int, Int] // Right(12)
l.right.map(_.toDouble): Either[String, Double] // Left("flower")
r.right.map(_.toDouble): Either[String, Double] // Right(12.0)
Like with other types which define a map
method, the same can be achieved
using a for-comprehension:
for (s <- l.left) yield s.size // Left(6)
To support multiple projections as generators in for-comprehensions, the Either
type also defines a flatMap
method.
- Source
- Version
- 1.0, 11/10/2008
- Since
- 2.7
final case class Failure[+T](exception: Throwable) extends Try[T] with Product with Serializable
final case class Left[+A, +B](a: A) extends Either[A, B] with Product with Serializable
The left side of the disjoint union, as opposed to the scala.util.Right side.
- Source
- Version
- 1.0, 11/10/2008
class MurmurHash[T] extends (T) ⇒ Unit
A class designed to generate well-distributed non-cryptographic hashes. It is designed to be passed to a collection’s foreach method, or can take individual hash values with append. Its own hash code is set equal to the hash code of whatever it is hashing.
- Annotations
- @ deprecated
- Deprecated
- (Since version 2.10.0) Use the object MurmurHash3 instead.
- Source
class Random extends Serializable
final case class Right[+A, +B](b: B) extends Either[A, B] with Product with Serializable
The right side of the disjoint union, as opposed to the scala.util.Left side.
- Source
- Version
- 1.0, 11/10/2008
final case class Success[+T](value: T) extends Try[T] with Product with Serializable
sealed abstract class Try[+T] extends Product with Serializable
The Try
type represents a computation that may either result in an exception,
or return a successfully computed value. It’s similar to, but semantically
different from the scala.util.Either type.
Instances of Try[T]
, are either an instance of scala.util.Success [T] or
scala.util.Failure [T].
For example, Try
can be used to perform division on a user-defined input,
without the need to do explicit exception-handling in all of the places that an
exception might occur.
Example:
import scala.io.StdIn
import scala.util.{Try, Success, Failure}
def divide: Try[Int] = {
val dividend = Try(StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt)
val divisor = Try(StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt)
val problem = dividend.flatMap(x => divisor.map(y => x/y))
problem match {
case Success(v) =>
println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v)
Success(v)
case Failure(e) =>
println("You must've divided by zero or entered something that's not an Int. Try again!")
println("Info from the exception: " + e.getMessage)
divide
}
}
An important property of Try
shown in the above example is its ability to _
pipeline_ , or chain, operations, catching exceptions along the way. The
flatMap
and map
combinators in the above example each essentially pass off
either their successfully completed value, wrapped in the Success
type for it
to be further operated upon by the next combinator in the chain, or the
exception wrapped in the Failure
type usually to be simply passed on down the
chain. Combinators such as recover
and recoverWith
are designed to provide
some type of default behavior in the case of failure.
Note : only non-fatal exceptions are caught by the combinators on Try
(see
scala.util.control.NonFatal). Serious system errors, on the other hand, will be
thrown.
Note: : all Try combinators will catch exceptions and return failure unless otherwise specified in the documentation.
Try
comes to the Scala standard library after years of use as an integral
part of Twitter’s stack.
- Source
- Since
- 2.10
Value Members
object Either extends Serializable
object Properties extends PropertiesTrait
Loads library.properties
from the jar.
object Random extends Random
The object Random
offers a default implementation of scala.util.Random and
random-related convenience methods.
- Source
- Since
- 2.8
object Sorting
The Sorting
object provides convenience wrappers for java.util.Arrays.sort
.
Methods that defer to java.util.Arrays.sort
say that they do or under what
conditions that they do.
Sorting
also implements a general-purpose quicksort and stable (merge) sort
for those cases where java.util.Arrays.sort
could only be used at the cost of
a large memory penalty. If performance rather than memory usage is the primary
concern, one may wish to find alternate strategies to use
java.util.Arrays.sort
directly e.g. by boxing primitives to use a custom
ordering on them.
Sorting
provides methods where you can provide a comparison function, or can
request a sort of items that are scala.math.Ordered or that otherwise have an
implicit or explicit scala.math.Ordering.
Note also that high-performance non-default sorts for numeric types are not provided. If this is required, it is advisable to investigate other libraries that cover this use case.
- Source
- Version
- 1.1
object Try extends Serializable
package control
package hashing
package matching
Full Source:
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala
package util
/** An implementation of Austin Appleby's MurmurHash 3.0 algorithm
* (32 bit version); reference: http://code.google.com/p/smhasher
*
* This is the hash used by collections and case classes (including
* tuples).
*
* @author Rex Kerr
* @version 2.9
* @since 2.9
*/
import java.lang.Integer.{ rotateLeft => rotl }
import scala.collection.Iterator
/** A class designed to generate well-distributed non-cryptographic
* hashes. It is designed to be passed to a collection's foreach method,
* or can take individual hash values with append. Its own hash code is
* set equal to the hash code of whatever it is hashing.
*/
@deprecated("Use the object MurmurHash3 instead.", "2.10.0")
class MurmurHash[@specialized(Int,Long,Float,Double) T](seed: Int) extends (T => Unit) {
import MurmurHash._
private var h = startHash(seed)
private var c = hiddenMagicA
private var k = hiddenMagicB
private var hashed = false
private var hashvalue = h
/** Begin a new hash using the same seed. */
def reset() {
h = startHash(seed)
c = hiddenMagicA
k = hiddenMagicB
hashed = false
}
/** Incorporate the hash value of one item. */
def apply(t: T) {
h = extendHash(h,t.##,c,k)
c = nextMagicA(c)
k = nextMagicB(k)
hashed = false
}
/** Incorporate a known hash value. */
def append(i: Int) {
h = extendHash(h,i,c,k)
c = nextMagicA(c)
k = nextMagicB(k)
hashed = false
}
/** Retrieve the hash value */
def hash = {
if (!hashed) {
hashvalue = finalizeHash(h)
hashed = true
}
hashvalue
}
override def hashCode = hash
}
/** An object designed to generate well-distributed non-cryptographic
* hashes. It is designed to hash a collection of integers; along with
* the integers to hash, it generates two magic streams of integers to
* increase the distribution of repetitive input sequences. Thus,
* three methods need to be called at each step (to start and to
* incorporate a new integer) to update the values. Only one method
* needs to be called to finalize the hash.
*/
@deprecated("Use the object MurmurHash3 instead.", "2.10.0")
// NOTE: Used by SBT 0.13.0-M2 and below
object MurmurHash {
// Magic values used for MurmurHash's 32 bit hash.
// Don't change these without consulting a hashing expert!
final private val visibleMagic = 0x971e137b
final private val hiddenMagicA = 0x95543787
final private val hiddenMagicB = 0x2ad7eb25
final private val visibleMixer = 0x52dce729
final private val hiddenMixerA = 0x7b7d159c
final private val hiddenMixerB = 0x6bce6396
final private val finalMixer1 = 0x85ebca6b
final private val finalMixer2 = 0xc2b2ae35
// Arbitrary values used for hashing certain classes
final private val seedString = 0xf7ca7fd2
final private val seedArray = 0x3c074a61
/** The first 23 magic integers from the first stream are stored here */
val storedMagicA =
Iterator.iterate(hiddenMagicA)(nextMagicA).take(23).toArray
/** The first 23 magic integers from the second stream are stored here */
val storedMagicB =
Iterator.iterate(hiddenMagicB)(nextMagicB).take(23).toArray
/** Begin a new hash with a seed value. */
def startHash(seed: Int) = seed ^ visibleMagic
/** The initial magic integers in the first stream. */
def startMagicA = hiddenMagicA
/** The initial magic integer in the second stream. */
def startMagicB = hiddenMagicB
/** Incorporates a new value into an existing hash.
*
* @param hash the prior hash value
* @param value the new value to incorporate
* @param magicA a magic integer from the stream
* @param magicB a magic integer from a different stream
* @return the updated hash value
*/
def extendHash(hash: Int, value: Int, magicA: Int, magicB: Int) = {
(hash ^ rotl(value*magicA,11)*magicB)*3 + visibleMixer
}
/** Given a magic integer from the first stream, compute the next */
def nextMagicA(magicA: Int) = magicA*5 + hiddenMixerA
/** Given a magic integer from the second stream, compute the next */
def nextMagicB(magicB: Int) = magicB*5 + hiddenMixerB
/** Once all hashes have been incorporated, this performs a final mixing */
def finalizeHash(hash: Int) = {
var i = (hash ^ (hash>>>16))
i *= finalMixer1
i ^= (i >>> 13)
i *= finalMixer2
i ^= (i >>> 16)
i
}
/** Compute a high-quality hash of an array */
def arrayHash[@specialized T](a: Array[T]) = {
var h = startHash(a.length * seedArray)
var c = hiddenMagicA
var k = hiddenMagicB
var j = 0
while (j < a.length) {
h = extendHash(h, a(j).##, c, k)
c = nextMagicA(c)
k = nextMagicB(k)
j += 1
}
finalizeHash(h)
}
/** Compute a high-quality hash of a string */
def stringHash(s: String) = {
var h = startHash(s.length * seedString)
var c = hiddenMagicA
var k = hiddenMagicB
var j = 0
while (j+1 < s.length) {
val i = (s.charAt(j)<<16) + s.charAt(j+1)
h = extendHash(h,i,c,k)
c = nextMagicA(c)
k = nextMagicB(k)
j += 2
}
if (j < s.length) h = extendHash(h,s.charAt(j).toInt,c,k)
finalizeHash(h)
}
/** Compute a hash that is symmetric in its arguments--that is,
* where the order of appearance of elements does not matter.
* This is useful for hashing sets, for example.
*/
def symmetricHash[T](xs: scala.collection.TraversableOnce[T], seed: Int) = {
var a,b,n = 0
var c = 1
xs.seq.foreach(i => {
val h = i.##
a += h
b ^= h
if (h != 0) c *= h
n += 1
})
var h = startHash(seed * n)
h = extendHash(h, a, storedMagicA(0), storedMagicB(0))
h = extendHash(h, b, storedMagicA(1), storedMagicB(1))
h = extendHash(h, c, storedMagicA(2), storedMagicB(2))
finalizeHash(h)
}
}
Interested in Scala?
I send out weekly, personalized emails with articles and conference talks.
Subscribe now.