Skip to content

Instantly share code, notes, and snippets.

View deanwampler's full-sized avatar

Dean Wampler deanwampler

View GitHub Profile
// Adapted from:
// https://github.com/deanwampler/programming-scala-book-code-examples/blob/master/src/main/scala/progscala3/typesystem/typelambdas/Functor.scala
// https://github.com/deanwampler/programming-scala-book-code-examples/blob/master/src/script/scala/progscala3/typesystem/typelambdas/Functor.scala
// import the.package.given // If the givens were defined in package or object somewhere.
scala> Seq(1,2,3).map2(_ * 2.2)
| Nil.map2(_.toString)
val res0: Seq[Double] = List(2.2, 4.4, 6.6000000000000005)
val res1: Seq[String] = List()
// Adapted from:
// https://github.com/deanwampler/programming-scala-book-code-examples/blob/master/src/main/scala/progscala3/typesystem/typelambdas/Functor.scala
trait Functor[M[_]]:
extension [A] (m: M[A]) def map2[B](f: A => B): M[B]
given Functor[Seq] with
extension [A] (seq: Seq[A]) def map2[B](f: A => B): Seq[B] = seq map f
given Functor[Option] with
import Matrix.`*`
def `1 + 1 == 2 test` = assert(1+1 == 2) // Readable test names!
def contains(i: Int, seq: Seq[Int]): Boolean = seq match {
case Nil => false
case `i` +: _ => true // Must use back ticks, or i is just a new variable that shadows the method argument.
case _ +: tail => contains(i, tail)
}
def count[T](ts: T*): Int = ts.size
val seq = Seq(1,2,3)
count(seq) // Returns 1!
count(seq*) // Returns 3. Use seq* instead of seq: _*
Seq('a', 'b', 'c', 'd', 'e') match {
case Seq('a', tail*) => s"Found a, $tail" // Instead of Seq('a', tail: _*)
case Seq('b', _*) => "Found b" // Instead of Seq('a', _: _*)
case seq => s"Other list: $seq"
}
class Authenticate(authService: AuthService):
private var authenticated = false
def isAuthenticated: Boolean = authenticated
final def apply(username: String, password: String): Boolean =
authenticated = ...
authenticated
object Service:
def doStuff[T](f: => T): Try[T] = ...
import scala.util.* // Instead of _
import scala.concurrent.{given, *} // Everything in concurrent, including givens
import java.util.Queue as JQueue // "as" replaces => and no braces needed for one import
import java.util.{HashMap as _, *} // Need {} for a list. Still use _ to hide HashMap
// Input a sequence of any element type and constructs a string:
def tos(seq: Seq[?]): String = seq.mkString("[", ", ", "]")
tos(Vector(1,2,3)) // "[1, 2, 3]"
// A reminder of given imports, but specifically how to import all
// givens of a parameterized type:
trait Marker[T]
object Obj:
given Marker[Int] with {}
given Marker[List[?]] with {}
case class User(name: String, password: String)
def checkName(user: User): Either[String,User] =
if (user.name.isEmpty) Left("Empty name")
else Right(user)
def checkPassword(user: User): Either[String,User] =
if (user.password.length < 8) Left("Password needs 8+ characters")
else Right(user)
// Type parameter placeholder: S[_]
def str[T, S[_]](ss: S[T]): String = ss.toString
val s1 = str(Seq(1, 2, 3)) // "List(1, 2, 3)"
// Function parameter placeholder: _.toUpperCase
val loud = Seq("hello world!").map(_.toUpperCase) // List(HELLO WORLD!)
// Match placeholder: _ in the first two case clauses
Seq(Seq('a', 'b', 'c'), Seq(1, 2, 3), Seq(1.1, 2.2)).map {
seq => seq match {
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.*
object FutureCF:
type Executable[T] = ExecutionContext ?=> T
// Compare Future.apply's signature:
// apply[T](body: => T)(implicit executor: ExecutionContext): Future[T]
def apply[T](body: => T): Executable[Future[T]] = Future(body)