Scala Flashcards
var x = 5
variable
val x = 5
constant
x = 5
constant, bad form!
var x: Double = 5
explicit type
def f(x: Int) = { x*x }
define function
def f(x: Int) { x*x }
error: without “=” it’s a Unix-returning procedure
def f(x: Any) = println(x)
Any is the root of the Scala class hierarchy. This function can take anything for parameter.
def f(x) = println(x)
Syntax error: must have a type for every arg.
type R = Double
type alias
call by? def f(x: R)
call-by-value
call by? def f(x: => R)
call-by-name (lazy parameters)
(x:R) => x*x
anonymous function
(1 to 5).map(*2)
or
(1 to 5).reduceLeft(+_)
anonymous function - underscore is positionally matched argument
(1 to 5).map( x => x*x )
anonymous function: to use an argument twice, you have to name the variable
(1 to 5).map(2)
or
(1 to 5).map(2)
anonymous function bound infix method. Use 2*_ instead.
(1 to 5).map {val x=_*2; println(x); x}
anonymous function - block style returns last expression
(1 to 5) filter {%2 == 2} map {*2}
anonymous function - pipeline style.
def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x)) val f = compose({_*2),{_-1})
anonymous function - to pass in multiple blocks, need outer parenthesis
val zscore =
(mean:R, sd:R) =>
(x:R) =>
(x-mean)/sd
currying
def zscore(mean:R, sd:R) =
(x:R) =>
(x-mean)/sd
currying
def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd
currying (syntax sugar)
val normer = zscore(7, 0.4)_
need trailing underscore to get the partial, only for the sugar version
def mapmakeT(seq: List[T]) = seq.map(g)
generic type
5.+(3); 5 + 3
1 to 5) map (_*2
infix sugar