You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.6 KiB
Plaintext

// define function
// GOOD
def f(x: Int) = { x*x }
// BAD
// hidden error: without = its a Unit-returning procedure; causes havoc
def f(x: Int) { x*x }
// define function
// GOOD
def f(x: Any) = println(x)
// BAD
// syntax error: need types for every arg.
def f(x) = println(x)
// type alias
type R = Double
// call-by-value
def f(x: R)
// call-by-name (lazy parameters)
def f(x: => R)
// anonymous function
(x:R) => x*x
// anonymous function: underscore is positionally matched arg.
(1 to 5).map(_*2) // vs.
(1 to 5).reduceLeft( _+_ )
// anonymous function: to use an arg twice, have to name it.
(1 to 5).map( x => x*x )
// anonymous function: bound infix method. Use 2*_ for sanitys sake instead.
// GOOD
(1 to 5).map(2*)
// BAD
(1 to 5).map(*2)
// anonymous function: block style returns last expression.
(1 to 5).map { x => val y=x*2; println(y); y }
// anonymous functions: pipeline style. (or parens too).
(1 to 5) filter {_%2 == 0} map {_*2}
// anonymous functions: to pass in multiple blocks, need outer parens.
def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x))
val f = compose({_*2}, {_-1})
// currying, obvious syntax.
val zscore = (mean:R, sd:R) => (x:R) => (x-mean)/sd
// currying, obvious syntax
def zscore(mean:R, sd:R) = (x:R) => (x-mean)/sd
// currying, sugar syntax. but then:
def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd
// need trailing underscore to get the partial, only for the sugar version.
val normer = zscore(7, 0.4) _
// generic type.
def mapmake[T](g:T=>T)(seq: List[T]) = seq.map(g)
// infix sugar.
5.+(3); 5 + 3
(1 to 5) map (_*2)
// varargs
def sum(args: Int*) = args.reduceLeft(_+_)