alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (STUsage.scala)

This example Scala source code file (STUsage.scala) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

app, classtag, forall, immutablearray, int, list, s\=, stusage

The STUsage.scala Scala example source code

package scalaz.example

import reflect.ClassTag

object STUsage extends App {
  import scalaz._
  import std.list._
  import std.string._
  import std.anyVal._
  import syntax.equal._
  import effect._
  import ST._

  // Creates a new mutable reference and mutates it
  def e1[A] = for {
    r <- newVar[A](0)
    x <- r.mod(_ + 1)
  } yield x

  // Creates a new mutable reference, mutates it, and reads its value.
  def e2[A] = e1[A].flatMap(_.read)

  // Run e2, returning the final value of the mutable reference.
  def test = new Forall[ST[?,Int]] {
    def apply[A] = e2
  }

  // Run e1, returning a mutable reference to the outside world.
  // The type system ensures that this can never be run.
  def test2 = new Forall[λ[S=>ST[S,STRef[S,Int]]]] {
    def apply[A] = e1
  }

  val compiles = runST(test)

  // Does not compile because it would expose a mutable reference.
  // val doesNotCompile = runST(test2)

  // Bin-sort a list into an immutable array.
  // Uses a non-observable mutable array in the background.
  def binSort[A: ClassTag](size: Int, key: A => Int, as: List[A]): ImmutableArray[List[A]] =
    accumArray(size, (vs: List[A], v: A) => v :: vs, List(), for { a <- as } yield (key(a), a))

  assert(binSort(12, (_: String).length, List("twenty four", "one", "")).toList.flatten === List("", "one", "twenty four"))
  assert(compiles === 1)
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala STUsage.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.