map
(1 to 10).map(x => x * x)
def triple(x: Int) = 3 * x
(1 to 10).map(triple)
def quadruple(x: Int) = 4 * x (1 to 10).map(quadruple)
(1 to 10).map(multiplyBy(5))
multiplyBy(5)
needs to produce a function...Int => Int
:
def multiplyBy(n: Int) : Int => Int = ...
... = (x: Int) => ...
n * x
.def multiplyBy(n: Int) : Int => Int = (x: Int) => n * x
def multiplyBy(n: Int) = (x: Int) => n * x
List(1, 2, 3).sortWith(_ > _)
strings.sortWith(comparingBy(s => s.length())
comparingBy
produce?
(String, String) => Boolean
comparingBy
consume?
String => Integer
def comparingBy(f: String => Integer) =
(x: String, y: String) => ... // A Boolean
... => f(x) < f(y)
comparingBy
generic.
def comparingBy[T, R : Ordering](f: T => R) = { // Don't worry about the details import scala.Ordered.orderingToOrdered (x: T, y: T) => f(x) < f(y) }
Person => String
:
case class Person(first: String, last: String) val people = List(Person("Fred", "Flintstone"), Person("Fred", "Brooks"), Person("Barney", "Rubble")) people.sortWith(comparingBy(_.first))
people.sortWith(breakingTies(comparingBy(_.first), comparingBy(_.last)))
breakingTies
produce?(Person, Person) => Boolean
breakingTies
consume?(Person, Person) => Boolean
def breakingTies(c1: (Person, Person) => Boolean, c2: (Person, Person) => Boolean) =
(x: Person, y: Person) => ... // A Boolean
=> if (c1(x, y)) true else if (c1(y, x)) false else c2(x, y)
def multiply(x : Int, y : Int) = x * y multiply(3, 4) is 12
def multiply(x : Int)(y : Int) = x * y multiply(3)(4) is 12
multiply(3)
? def multiply(x: Int) = (y: Int) => x * y // That's our multiplyBy
def comparingBy(f: String => Integer) = (x: String, y: String) => f(x) < f(y) def comparingBy(f: String => Integer)(x: String, y: String) = f(x) < f(y)
val
to a def
:
val triple = (x: Int) => 3 * x def triple(x: Int) = 3 * x
lab4/report.txt
inside the Git repo. Include the coder's name in the report! Define a variable lst
as
val lst = List("Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf")
What is the shortest command you can use to
lst
reduce
)makeMin
that consumes a comparator (a function (String, String) => Boolean
) and produces a function (a: String, b: String) => String
that computes the smaller of the two inputs, as measured by the comparator.String
with T
and stick a [T]
right after the function name. Don't worry—it won't hurt a bit.def max(lst : List[String], less : (String, String) => Boolean) = lst.reduce((x, y) => if (less(x, y)) y else x)
Make a call to max
that yields the longest string in a list lst
. Use _
for the string parameters in your less
function.
def max[T](lst : List[T], less : (T, T) => Boolean) = lst.reduce((x, y) => if (less(x, y)) y else x)
What happens when you call max(lst, _ < _)?
max[T]
function, exactly like multiply
above. What is the code for your revised function? What happens when you call max(lst)(_ < _)
?
(Why does this work? Now the Scala type inferencer knows that T
must be String
after processing max(lst)
.)