프로그래밍/Scala
HW 1. Exercise 1-2 보충
잠이안와
2022. 10. 2. 03:24
저번에 대충 짜둔게 있긴한데 stackoverflow가 떠서 ^__^;;
반타작만 할 순 없으므로 일단 할 수 있을 때까지 해봄
가 보 자 고

다시 올리는 문제
/**
* Exercise 1-2: fold
*
* Calculate f(a, f(a + 1, f(a + 2, ... f(b - 1, b)))) `(0 <= a, b <= 10^6)`
*
* when a >= b, return 0
*
* We guarantee that any (f, a, b) in the test set will not raise integer overflow.
*/
def fold(f: (Long, Long) => Long, a: Long, b: Long): Long = ???
다시 생각해낸 solution
def fold(f: (Long, Long) => Long, a: Long, b: Long): Long = {
def putting(a: Long, b: Long, f: (Long, Long) => Long, res: Long = b):Long = {
if (a == b) res
else {
val new_res = f(b - 1, res)
putting(a, b - 1, f, new_res)
}
}
if (a >= b) 0
else putting(a, b, f)
}
def sub(a:Long, b:Long):Long = a-b
fold(sub,5L,1000000L)
//val res0: Long = -499998
//(fold(sub, 5L, 1000000L) == -499998L)
나 머임.....
왜 새벽에 집중 잘함.....

풀어버려따 꺄ㅑ