- 함수
- 함수를 변수에 저장할 수 있따. (functional language의 가장 큰 특징 중 하나)
- 함수를 인자로 쓸 수 있고, 함수를 리턴할 수 있다 (high-order function의 특징, 추후에 다시 설명)
- function type
- arrow로 표시 가능
- type1 → type2
- type1 : 인자 타입, type2 : expression type
- function body expression type
- f(x, y, z) ⇒ f(x)(y)(z)
- f: int x int x int → int ⇒ f: int → int → int → int
e.g. let inc x = x+ 1;; ⇒ (* inc int → int *)let sum x y = x + y in (* sum : int → int → int *)let res = sum’ 3 in (* res : int , y가 3으로 바인딩 *)
- 함수를 인자로 받는 경우
- 함수를 리턴값으로 받는 경우
- f(x, y, z) ⇒ f(x)(y)(z)
- Format.printf “Sum2: %d\n” (sum 1 3)
- let f = sum 1 in (* f: int → int ; 입력 인자가 없는 것 같지만 sum 자체가 인자이기 때문에 int가 인자, expression body가 int 형*)
- let _ = Format.printf “Inc: %d \n” (app inc 3) in
- let inc x = x + 1 in (* inc : int → int ; 인자 int, body int*)
- Format.printf “Result: %d\n” res
- let sum’ = sum 1 in (* sum’ : int → int , x가 1로 바인딩 *)
- let inc x y= x+ y;; ⇒ (* inc : int → int → int *)
- tuple
- tuple 형은 type * type으로 씀→ let p = 3, 4 (*p: int * int *)→ let sum (x, y) = x + y in Format.printf “Result: %d\n” (sum (1,3)) ;;
- ⇒ (* sum : int * int → int *)
- → let q = (3, ‘c’, “hi”) (* q: int * char * string *)
- → (1, “hi”) : int * string
- Recursive function
- rec keyword 쓰지 않으면,,, 재귀 호출되지 않음! 주의!
- 조건문
- 비교 대상 간 type 잘 맞춰줘야 함, 그리고 조건문에 따른 return value 타입도 잘 맞춰야 함
- type inference
- let sum_if_true test first second =(if test second then second else 0);;
- (int → bool) → int → int → int
- (if test first then first else 0) +
- Syntax : 문법, Semantic: 의미 → syntax는 달라도 semantic이 동일할 수 있음
- Lexical Scope vs Dynamic Scope
- Lexical Scope (정적 scope) : 컴파일 시점에서 identifier의 scope가 결정된다 → early-binding
- Dynamic Scope (동적 scope) : 런타임 시 identifier의 scope이 결정된다 → late-binding
- Lexical Scope (정적 scope) : 컴파일 시점에서 identifier의 scope가 결정된다 → early-binding
반응형
'프로그래밍언어' 카테고리의 다른 글
[프로그래밍언어] 20가지 예제로 준비하는 기말고사 (1) (0) | 2024.03.25 |
---|---|
[프로그래밍언어] 20가지 예제로 준비하는 중간고사 (3) (0) | 2024.03.25 |
[프로그래밍언어] 20가지 예제로 준비하는 중간고사 (2) (0) | 2024.03.25 |
[프로그래밍언어] 20가지 예제로 준비하는 중간고사 (1) (0) | 2024.03.25 |