본문 바로가기

프로그래밍언어

[프로그래밍언어] 20가지 예제로 준비하는 기말고사 (2)

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