map function from lab 2
val triple = (x : Int) => 3 * x (1 to 10).map(triple) // yields 3 6 9 12 ... 30
IntList[Int], function (Int) =>
Int, returns List[Int]
def map(lst : List[Int], fun: (Int) => Int) : List[Int] =
Nil, otherwise apply fun
to lst.head and use recursion:
if (lst.isEmpty) Nil else fun(lst.head) :: map(lst.tail, fun)
map(List(1, 2, 3), (x : Int) => 3 * x)
What should
mapdo with each element inlst?
val n = 3 val fun = (x : Int) => n * x // What is fun(2)?
n is not defined in the scope of fun, but that
is ok. In the body of a function, you can use any variable from the
enclosing scope.n is immutable, so it will
always be 3. But consider this:
def mulBy(n : Int) = (x : Int) => n * x
val quadruple = mulBy(4) // the function (x : Int) => 4 * x
quadruple(5) // yields 20
mulBy yields a different function.nval textArea = new JTextArea(20, 50)
val button1 = new JButton("Click Me!")
button1.addActionListener((e : ActionEvent) => {
textArea.append("I was clicked\n")
})
textAreafinal JTextArea textArea = new JTextArea(20, 50);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.append("Hello\n");
}
};

val isEven = (x : Int) => x % 2 == 0
(1 to 10).filter(isEven). As always, don't type the
period, but type ENTER. What do you get?
HINT: These “What do you get” exercises are a lot more effective when you and your buddy first discuss whar you think you'll get. “Form a hypothesis” is an essential part of the learning path.
filter does.val gen = new Random gen.nextInt(10) gen.nextInt(10)
randList(len : Int, n : Int) :
List[Int] that makes a list of length len of random
integers between 0 and n - 1. For example, randList(5,
10) might yield a list of numbers 5 1 2 0 9. Define
randList as a recursive function. What is the code of your
function?
Hint: If len is 0, the result is nil.
Otherwise, it is gen.nextInt(n) :: something. What is your
definition?
Note: You need not define gen. You
already defined it in part 1. Just use it.
randList(5, 1000)? For
randList(1000, 5)?randList a closure? greaterThan100(lst : List[Int]) that
returns only those integers in lst that are greater than 100.
Don't use recursion; simply call filter with an appropriate
function:
def greaterThan100(lst : List[Int]) = {
val fun = ... // your work
lst.filter(fun) // NOTE: The last expression in a { ... } is its value
}
What is your function's code?
greaterThan100(randList(10, 200))? Why
does that give you confidence that you implemented everything correctly?
def greaterThan(n : Int, lst : List[Int]) = {
val fun = ... // your work
lst.filter(fun)
}
For example, greaterThan(50, nums) yields all values of
nums > 50.
What is the code of your greaterThan function?
greaterThan(100, randList(10, 200))?
fun inside greaterThan a
closure?Do this if you have extra time.
frame.setVisible(false). How did you do that?