[scala] 개인 정리 노트1

오현우·2022년 11월 28일
0

모든 loop는 값으로 대체될 수 있다.

스칼라에서 재귀 함수를 종용하는 이유!!!!

def loop: Int = loop

해당 함수는 자기 자신을 호출하면서 무한 루프를 만들어낸다. 즉 value를 통해 loop를 생성해 낸다. 나는 스칼라에서 억지 재귀인줄 알았다... ㅠㅠㅠ

scala`s evaluate strategy

스칼라는 처음으로는 call by value 전략을 채용하고 있다.
두번째는 call by name 이다.

call by name은 해당 함수에서 호출 되기전까지 해당 아규먼트를 계산하지 않는 방법이다.

call by value는 2번 이상 반복 계산을 수행하지 않기 위해 야규먼트 내부에 존재하는 것들을 먼저 계산하고 분배하는 방식이다.

구체적인 예시를 아래에서 확인하자.

def square(x: Int): Int = x * x
def sumOfSquare(x: Int, y: Int): Int = square(x) + square(y)

sumOfSquare(2, 2+2)를 우리가 호출한다고 가정해보자.
스칼라 인터프리터는 아래와 같은 방식으로 동작한다.

square(2) + square(2+2)
2 * 2 + square(2+2)
4 + square(2+2)
4 + (2+2) * (2+2)
4 + 4 * (2+2)
4 + 4 * 4
4 + 16
20

CBN CBV 핵심내용

항상 CBN evaluate은 CBV evaluate가 종료된다면 반드시 종료되지만 역은 성립하지 않는다.

square(x: Int, y: loop): Int = x * x  

구체적인 예시는 위에서 square(x, loop) 로 설명이 가능하다.
CBV는 무한루프에 빠지지만 CBN은 x만 확인하면 되므로 루프에 빠지지 않게 된다.

스칼라에서 CBN, CBV 쓰는법!!

CBV의 경우 일반적인 상황에서 스칼라가 대부분 채택하는 방식이다.
CBN의 경우 y:() => Int 이러한 방식이나 y: => Int 이러한 방식으로 CBN 방식을 채택할 수 있다. 컴파일러나 인터프리터가 해당 노테이션을 힌트 삼아 채용한다!!

CBV가 디폴트인 이유!!

  • One reason is that a call-by-value can avoid sometimes exponentially many reduction steps because it avoids duplication of evaluations.

  • The second reason is that as long as a language has some imperative side effects, which is the case for Scala, call-by-value is actually much more predictable than call-by-name. That means it's much easier to tell when the effects of an expression actually happen if the evaluation strategy is call-by-value than if it is call-by-name.

profile
핵심은 같게, 생각은 다르게

0개의 댓글