Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Lab 1

Functional Programming
Start Eclipse and make a new Scala project: File -> New -> Project -> Scala Wizards -> Scala
Project -> Next. Give a name lab1 and click Finish. Right-click on the project in the Package
Explorer, then select Scala -> Create Scala Interpreter.
1.
a) How do you get the squares of the numbers from 1 to 10?
b) How do you get the squares of the numbers from 1 to 10 without using val? Hint:
Anonymous functions
2. Write a function that check whether the number is even.
3. Write a Scala function pow(x : Double, n : Int) : Double that return a
power xn. Hint: think recursively.
For example:
pow(2,0) return 1
pow(2,3) return 8
4. Make a list of the elements 1, 2, 3, 5, 7.
Write 2 functions (dont use Scala library functions: append, reverse):
append(a : List[Int], b : List[Int]) : List[Int]
reverse(a : List[Int]) : List[Int]
5. Write a Scala function greaterThan that returns a list of all numbers > given number in a
given list, following the sample code
def greaterThan(n : Int, lst : List[Int]) = {
val fun = ... // your work
lst.filter(fun)
}
For example, greaterThan(50, List(1, 55, 6, 2)) yields List(55)
Finish greaterThan function.
6. Curry the arguments in greaterThan function so that the following invocation is legal:
val filter = greaterThan(5) _
val result = filter (List(1, 2, 3, 4, 5, 6, 7) // List(6, 7)

7. Find out a function to:


a) Check whether a List[Int] have some elements equal with 0.
b) Select 3 elements from the third one of the List (if any). For example:
List(1,2,3,4,5,6,7,8) => List(3,4,5)
c) Look up the definition of span. Make an example that demonstrates how span works.
Hint: use scaladoc, try to search related functions of List
8. What is the shortest command you can use to
a) Remove all strings of length > 5 from a list
b) Sort a list of strings by increasing length
c) Find the longest string in a list
9. Horner's method for evaluating a polynomial uses folding, like in this example:
2x3 + 3x2 - x + 5= (((2 x + 3) x - 1) x + 5
Write a function evalPoly(coeffs : List[Double], x : Double) : Double
that computes the result using the /: operator.
For example, evalPoly(List(2, 3, -1, 5), 2) is 31
10. Give lst = List(1, 2). How can we get a string "(1 + 2)" using
mkString()?

You might also like