[PL] Introduction to Programming Languages Exercise 4

임승재·2023년 3월 30일

프로그래밍언어

목록 보기
3/6

Exercise 4.1

Implement a function incBy:

def incBy(l: List[Int], n: Int): List[Int] = ??? 

that takes a list of integers and an integer as arguments and increases every element of the list by the given integer. Use the map method.

def incBy(l: List[Int], n: Int): List[Int] = l.map(_ + n) 

Exercise 4.2

Implement a function gt:

def gt(l: List[Int], n: Int): List[Int] = ??? 

that takes a list of integers and an integer as arguments and filters elements less than or equal to the given integer out from the list. Use the filter method.

def gt(l: List[Int], n: Int): List[Int] = l.filter(_ > n)

Exercise 4.3

Implement a function append:

def append(l: List[Int], n: Int): List[Int] = ??? 

that takes a list of integers and an integer as arguments and returns a list obtained by appending the integer at the end of the list. Use the foldRight method.

def append(l: List[Int], n: Int): List[Int] = 
  l.foldRight(List(n))((current, accumulator) => current::accumulator)

foldRight's List(n) that first parameter mean starting point for the accumulator. foldRight get second parameter by (current, accumulator) order, foldLeft get second parameter by (accumulator, current). I think the reason is that we're ordering the parameters of the function to be used as parameters according to the actual order of operations.

Exercise 4.4

Implement a function reverse:

def reverse(l: List[Int]): List[Int] = ??? 

that takes a list of integers and returns a list obtained by reversing the order between the elements. Use the foldLeft method.

def reverse(l: List[Int]): List[Int] = 
	l.foldLeft(Nil:List[Int])((acc, cur) => cur :: acc)
profile
KAIST Computer Science

0개의 댓글