Skip to content

Instantly share code, notes, and snippets.

@LambdaSix
Last active December 15, 2015 17:59
Show Gist options
  • Save LambdaSix/5300793 to your computer and use it in GitHub Desktop.
Save LambdaSix/5300793 to your computer and use it in GitHub Desktop.
Scala for-comprehension
class Person(val name: String, val female: Boolean)
val people = List(
new Person("Cliffy", false),
new Person("Ewing", true),
new Person("Tolkein", false),
new Person("Donna", true))
// Traverse the list and print the names
for (person <- people)
println(person.name)
// Filter out females
for (person: Person <- people
if person.female)
println(person.name)
// Only return males called Tolkein
for (person: Person <- people
if !person.female
if person.name.Contains("Tolkein"))
println(person.name)
// Variable's inside for-comps
for {person: Person <- people
if !person.female;
name = person.name
if name.contains("Tolkein")}
println(name)
// Yielding
val names = for(person <- people) yield person.name
// Yielding tuple
val namesTuple = for(person <- people) yield (person.name, person.female)
// Yielding tuple and variables
val tuples = for { person: Person <- people
female = person.female
if !female
name = person.name
if name.contains("Tolkein")
} yield (name,female)
for (person <- tuples) println(person)
val things = ()
// Case classes
abstract class Thing
case class Foo(name: String) extends Thing
case class Bar(arg: String, body: Thing) extends Thing
case class Baz(f: Thing, v: Thing) extends Thing
// No 'new' required
Foo("x", Bar("y", Baz(Foo("x", Var("y")))))
// Constructor variables are public
val x = Foo("X")
println(x.name)
// Automatic equality
val x1 = Foo("X")
val x2 = Foo("X")
val y1 = Foo("Y")
println("" + x1 + " == " + x2 + "=> " + (x1 == x2))
println("" + x1 + " == " + y1 + "=> " + (x1 == y1))
// Pretty printer.
object ThingTest {
def printThing(thing: Thing) {
thing match {
case Foo(n) =>
print(n)
case Bar(x, b) =>
print("^" + x + ".")
printThing(b)
case Baz(f,v) =>
print("(")
printThing(f)
print(" ")
printThing(v)
print(")")
}
}
def isIdentityBar(thing: Thing): Boolean = term match {
case Bar(x, Foo(y)) if x == y => true
case _ => false
}
val id = Bar("x", Foo("x"))
val t = Bar("x", Bar("x", Baz(Foo("x"), Foo("y"))))
printThing(t)
println
println(isIdentifyBar(id))
println(isIdentityBar(t))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment