OCaml ífl—로그랟밓

Size: px
Start display at page:

Download "OCaml ífl—로그랟밓"

Transcription

1 OCaml 프로그래밍 오학주 고려대학교정보대학컴퓨터학과 January 10 11, Blockchain Camp

2 소개 소속 : 고려대학교정보대학컴퓨터학과 전공 : 프로그래밍언어, 소프트웨어분석, 소프트웨어보안 웹페이지 :

3 강의내용 OCaml 프로그래밍 Part 1: 기초 OCaml 프로그래밍 (5 시간 ) 1. OCaml 기본구성 2. 리스트와재귀함수 3. 고차함수 4. 사용자정의타입 Part 2: 고급 OCaml 프로그래밍 (5 시간 )

4 Why OCaml?

5 프로그래밍언어순위 ( 인기순 )

6 프로그래밍언어랭킹 ( 연봉순 )

7 OCaml 및함수중심언어의활용사례

8 값중심, 함수중심프로그래밍언어 새롭고중요한생각의틀을제공 미래프로그래밍언어의청사진 프로그래밍언어의근본원리에대한이해 간결하고아름다운코드를작성하는즐거움... 소프트웨어전공자라면갖추어야하는기본소양

9 기본기

10 OCaml 의주요특징 값중심, 계산형, 함수중심프로그래밍 (Functional programming) 정적타입시스템 (Static type system) 자동타입추론 (Automatic type inference) 데이터타입, 패턴매칭 (Datatypes and pattern matching) 다형성 (Polymorphism) 모듈 (Modules) 메모리재활용 (Garbage Collection)

11 OCaml 프로그램의기본단위는식 프로그램을구성하는두단위 : 명령문 (statement): 기계상태를변경 x = x + 1 식 (expression): 상태변경없이값을계산 (x + y) * 2 프로그래밍언어를구분하는한가지기준 : 명령문을중심으로프로그램을작성 C, C++, Java, Python, JavaScript, etc often called imperative languages 식을중심으로프로그램을작성 ML, Haskell, Scala, Lisp, etc often called functional languages

12 OCaml 프로그램의기본구조 값정의들의나열 : let x 1 = e 1 let x 2 = e 2. let x n = e n 식 e 1, e 2,..., e n 을순차적으로계산 변수 x i 는식 e i 의값을지칭

13 예제 Hello World: let hello = "Hello" let world = "World" let helloworld = hello ^ " " ^ world let _ = print_endline helloworld 인터프리터를이용한실행 : $ ocaml helloworld.ml Hello World REPL 을이용한실행 : $ ocaml OCaml version # let hello = "Hello";; val hello : string = "Hello" # let world = "World";; val world : string = "World" # let helloworld = hello ^ " " ^ world;;

14 산술식 (Arithmetic Expressions) 숫값 ( 정수값, 실수값 ) 을계산하는식 # * 3;; - : int = 7 # *. 3.3;; - : float = 8.36 정수값을위한산술연산자 : a + b a - b a * b 덧셈뺄셈곱셈 a / b 나눗셈 ( 몫 ) a mod b 나눗셈 ( 나머지 ) 실수값을위한산술연산자 : +., -., *., /.,... 정수타입과실수타입을명확히구분 # ;; Error: This expression has type float but an expression was expected of type int # 3 + int_of_float 2.0;; - : int = 5

15 논리식 (Boolean Expressions) 논리값 ( 참, 거짓 ) 을계산하는식 # true;; - : bool = true # false;; - : bool = false 비교연산자 ( 산술식들로부터논리식을구성 ): # 1 = 2;; - : bool = false # 1 <> 2;; - : bool = true # 2 <= 2;; - : bool = true 논리연산자 ( 논리식들로부터새로운논리식을구성 ): # true && (false not false);; - : bool = true # (2 > 1) && (3 > 2);; - : bool = true

16 기본값 (Primitive Values) 프로그래밍언어에서기본적으로제공하는값 OCaml 은정수 (integer), 실수 (float), 논리 (boolean), 문자 (character), 문자열 (string), 유닛 (unit) 값을제공 # c ;; - : char = c # "Objective " ^ "Caml";; - : string = "Objective Caml" # ();; - : unit = ()

17 정적타입시스템 (Static Type System) 타입오류가있는프로그램은컴파일러를통과하지못함 : # 1 + true;; Error: This expression has type bool but an expression was expected of type int 발생가능한모든타입오류를실행전에찾아냄 OCaml 로작성된프로그램의안정성이높은이유

18 정적 / 동적타입시스템 타입시스템을기준으로한프로그래밍언어의구분 : 정적타입언어 (Statically typed languages) 타입체킹을컴파일시간에수행 타입오류를프로그램실행전에검출 C, C++, Java, ML, Scala, etc 동적타입언어 (Dynamically typed languages): 타입체킹을실행중에수행 타입오류를프로그램실행중에검출 Python, JavaScript, Ruby, Lisp, etc 정적타입언어들은다시두가지로구분 : 안전한 (Type-safe) 언어 : 타입체킹을통과한프로그램은실행중에타입오류가없음. 모든타입오류가실행전에검출됨. 프로그램이실행중에비정상적으로종료되지않음. ML, Haskell, Scala 안전하지않은 (Unsafe) 언어 : 타입체킹을통과해도실행중에여전히타입오류가발생가능 C, C++

19 장단점 정적타입언어 : (+) 타입오류가프로그램개발중에검출됨 (+) 실행중에타입체크를하지않으므로실행이효율적 ( ) 동적언어보다경직됨동적타입언어 : ( ) 타입오류가실행중에예상치못하게나타남 (+) 다양한언어특징을유연하게제공하기쉬움 (+) 쉽고빠른프로토타이핑

20 조건식 (Conditional Expression) if e 1 then e 2 else e 3 e 1 은반드시논리식이어야함. 즉 e 1 의값은참또는거짓 # if 1 then 2 else 3;; Error: This expression has type int but an expression was expected of type bool 조건식의값은 e 1 의값에따라서결정 # if 2 > 1 then 0 else 1;; - : int = 0 # if 2 < 1 then 0 else 1;; - : int = 1 e 2 와 e 3 는타입이같아야함 # if true then 1 else true;; Error: This expression has type bool but an expression was expected of type int

21 함수식 (Function Expression) fun x -> e 형식인자 (formal parameter) 가 x이고몸통 (body) 이 e인함수값 (function value) 을생성 함수의예 : fun x -> x + 1 fun y -> y * y fun x -> if x > 0 then x + 1 else x * x fun x -> fun y -> x + y fun x -> fun y -> fun z -> x + y + z 설탕구조 (syntactic sugar): fun x y -> x + y fun x y z -> x + y + z fun x 1 x n -> e

22 함수식 (Function Expression) # fun x -> x + 1;; - : int -> int = <fun> # fun y -> y * y;; - : int -> int = <fun> # fun x -> if x > 0 then x + 1 else x * x;; - : int -> int = <fun> # fun x -> fun y -> x + y;; - : int -> int -> int = <fun> # fun x -> fun y -> fun z -> x + y + z;; - : int -> int -> int -> int = <fun> # fun x y z -> x + y + z;; - : int -> int -> int -> int = <fun>

23 함수호출식 (Function Call) e 1 e 2 e 1 : 함수값을만들어내는식이어야함 e 2 : 함수전달인자 (actual parameter) # (fun x -> x * x) 3;; - : int = 9 # (fun x -> if x > 0 then x + 1 else x * x) 1;; - : int = 2 # (fun x -> if x > 0 then x + 1 else x * x) (-2);; - : int = 4 # (fun x -> fun y -> x + y) 1 2;; - : int = 3 # (fun x -> fun y -> fun z -> x + y + z) 1 2 3;; - : int = 6 e 2 는임의의식이가능 : # (fun f -> f 1) (fun x -> x * x);; - : int = 1 # (fun x -> x * x) ((fun x -> if x > 0 then 1 else 2) 3);; - : int = 1

24 Let Expression 값에이름붙이기 : let x = e 1 in e 2 e 1 의값을 x라고하고 e 2 를계산 x: 값의이름 ( 변수 ) e 1 : 정의식 (binding expression) e2 : 몸통식 (body expression) x 의유효범위 (scope) 는 e 2 # let x = 1 in x + x;; - : int = 2 # let x = 1 in x + 1;; - : int = 2 # (let x = 1 in x) + x;; Error: Unbound value x # (let x = 1 in x) + (let x = 2 in x);; - : int = 3

25 Let Expression e 1 과 e 2 는임의의식이될수있음 # let x = (let y = 1 in y + 1) in x + 1;; - : int = 3 # let x = 1 in let y = 2 in x + y;; - : int = 3 함수정의 : # let square = fun x -> x * x in square 2;; - : int = 4 # let add x y = x + y in add 1 2;; - : int = 3 재귀함수정의 : # let rec fact a = if a = 1 then 1 else a * fact (a - 1);; val fact : int -> int = <fun> # fact 5;; - : int = 120

26 연습문제 let a = 1 in let b = a + a in let c = b + b in c + c let x = 1 in let f y = x + y in let x = 2 in f x let x = 1 in ((let x = 2) + x)

27 함수값을자유롭게사용가능 프로그램에서함수도최대의자유도를가짐 (First-class values): 함수를지칭하는이름을만들수있음 : # let square = fun x -> x * x;; # square 2;; - : int = 4 함수를다른함수의인자로전달가능 : # let sum_if_true test first second = (if test first then first else 0) + (if test second then second else 0);; val sum_if_true : (int -> bool) -> int -> int -> int = <fun> # let even x = x mod 2 = 0;; val even : int -> bool = <fun> # sum_if_true even 3 4;; - : int = 4 # sum_if_true even 2 4;; - : int = 6

28 함수값을자유롭게사용가능 함수를다른함수의반환값으로전달가능 # let plus_a a = fun b -> a + b;; val plus_a : int -> int -> int = <fun> # let f = plus_a 3;; val f : int -> int = <fun> # f 1;; - : int = 4 # f 2;; - : int = 5 고차함수 (Higher-order function): 다른함수를인자로받거나반환하는함수. 언어의표현력을높이는주된특징.

29 패턴매칭 (Pattern Matching) 패턴매칭을이용한값의구조분석 팩토리얼예제 : let rec factorial a = if a = 1 then 1 else a * factorial (a - 1) let factorial a = match a with 1 -> 1 _ -> a * factorial (a - 1)

30 패턴매칭 (Pattern Matching) The nested if-then-else expression let isabc c = if c = a then true else if c = b then true else if c = c then true else false can be written using pattern matching: let isabc c = match c with a -> true b -> true c -> true _ -> false or simply, let isabc c = match c with a b c -> true _ -> false

31 자동타입추론 (Automatic Type Inference) C 나 Java 에서는타입을생략할수없음 : public static int f(int n) { int a = 2; return a * n; } OCaml 에서는타입을생략가능. 컴파일러가자동으로유추 : # let f n = let a = 2 in a * n;; val f : int -> int = <fun>

32 타입유추알고리즘 # let sum_if_true test first second = (if test first then first else 0) + (if test second then second else 0);; val sum_if_true : (int -> bool) -> int -> int -> int = <fun OCaml 컴파일러가타입을유추하는과정 : 1. The types of first and second must be int, because both branches of a conditional expression must have the same type. 2. The type of test is a function type α β, because test is used as a function. 3. α must be of int, because test is applied to first, a value of int. 4. β must be of bool, because conditions must be boolean expressions. 5. The return value of the function has type int, because the two conditional expressions are of int and their addition gives int.

33 타입을직접명시하는것도가능 # let sum_if_true (test : int -> bool) (x : int) (y : int) : int (if test x then x else 0) + (if test y then y else 0);; val sum_if_true : (int -> bool) -> int -> int -> int = <fun> 컴파일러가명시한타입이올바른지자동으로검증 : # let sum_if_true (test : int -> int) (x : int) (y : int) : int (if test x then x else 0) + (if test y then y else 0);; Error: The expression (test x) has type int but an expression was expected of type bool

34 다형타입 (Polymorphic Types) 아래프로그램의타입은? let id x = x OCaml 타입추론결과 : # let id x = x;; val id : a -> a = <fun> 임의의값에대해작동하는다형타입함수 : # id 1;; - : int = 1 # id "abc";; - : string = "abc" # id true;; - : bool = true 아래프로그램의타입은? let first_if_true test x y = if test x then x else y

35 예외처리 An exception means a run-time error: e.g., # let div a b = a / b;; val div : int -> int -> int = <fun> # div 10 5;; - : int = 2 # div 10 0;; Exception: Division_by_zero. The exception can be handled with try... with constructs. # let div a b = try a / b with Division_by_zero -> 0;; val div : int -> int -> int = <fun> # div 10 5;; - : int = 2 # div 10 0;; - : int = 0

36 예외처리 User-defined exceptions: e.g., # exception Problem;; exception Problem # let div a b = if b = 0 then raise Problem else a / b;; val div : int -> int -> int = <fun> # div 10 5;; - : int = 2 # div 10 0;; Exception: Problem. # try div 10 0 with Problem -> 0;; - : int = 0

37 리스트와재귀함수

38 튜플 (Tuples) 순서가있는값의묶음. 각구성요소는다른값을가질수있음 : # let x = (1, "one");; val x : int * string = (1, "one") # let y = (2, "two", true);; val y : int * string * bool = (2, "two", true) 패턴매칭을이용하여각구성요소를추출가능 : # let fst p = match p with (x,_) -> x;; val fst : a * b -> a = <fun> # let snd p = match p with (_,x) -> x;; val snd : a * b -> b = <fun> or equivalently, # let fst (x,_) = x;; val fst : a * b -> a = <fun> # let snd (_,x) = x;; val snd : a * b -> b = <fun>

39 튜플 (Tuples) let 에서패턴사용가능 : # let p = (1, true);; val p : int * bool = (1, true) # let (x,y) = p;; val x : int = 1 val y : bool = true

40 리스트 (Lists) 유한한원소들의나열 : # [1; 2; 3];; - : int list = [1; 2; 3] 순서가중요 : e.g., [3;4], [4;3], [3;4;3], [3;3;4] 모든원소가같은타입이어야함 [(1, "one"); (2, "two")] : (int * string) list [[]; [1]; [1;2]; [1;2;3]] : (int list) list 리스트의원소는변경이불가능 (immutable) 리스트의첫원소를 head, 나머지를 tail 이라고부름 # List.hd [5];; - : int = 5 # List.tl [5];; - : int list = []

41 리스트예제 # [1;2;3;4;5];; - : int list = [1; 2; 3; 4; 5] # ["OCaml"; "Java"; "C"];; - : string list = ["OCaml"; "Java"; "C"] # [(1,"one"); (2,"two"); (3,"three")];; - : (int * string) list = [(1, "one"); (2, "two"); (3, "thre # [[1;2;3];[2;3;4];[4;5;6]];; - : int list list = [[1; 2; 3]; [2; 3; 4]; [4; 5; 6]] # [1;"OCaml";3] ;; Error: This expression has type string but an expression was expected of type int

42 리스트를만드는방법 []: 빈리스트 (nil) :: (cons): 리스트의앞에하나의원소를추가 : # 1::[2;3];; - : int list = [1; 2; 3] # 1::2::3::[];; - : int list = [1; 2; 3] ([1; 2; 3] is a shorthand for (append): 두리스트를이어붙이기 : # [1; [3; 4; 5];; - : int list = [1; 2; 3; 4; 5]

43 리스트패턴 리스트를다룰때패턴매칭이매우유용하게쓰임 Ex1) 빈리스트인지검사하는함수 : # let isnil l = match l with [] -> true _ -> false;; val isnil : a list -> bool = <fun> # isnil [1];; - : bool = false # isnil [];; - : bool = true

44 리스트패턴 Ex2) 리스트의길이를구하는함수 : # let rec length l = match l with [] -> 0 h::t -> 1 + length t;; val length : a list -> int = <fun> # length [1;2;3];; - : int = 3 쓰이지않는구성요소는로대체가능 : let rec length l = match l with [] -> 0 _::t -> 1 + length t;; 리스트를다루는함수는주로재귀적으로정의

45 재귀적사고의강력함 Ex) 아래도형을그리는프로그램?

46 재귀적으로문제풀기 주어진문제의크기가충분히작다면직접푼다. 문제가충분히작지않다면, 1. 문제를동일한구조를가지는작은문제들로쪼갠다. 2. 쪼개진문제들을재귀적으로푼다. 3. 결과를합쳐서원래문제의답을구한다.

47 리스트길이구하기 (list length) # length [];; - : int = 0 # length [1;2;3];; - : int = 3 let rec length l = match l with [] -> 0 hd::tl -> 1 + length tl

48 예제 1: 리스트이어붙이기 (append) # append [1; 2; 3] [4; 5; 6; 7];; - : int list = [1; 2; 3; 4; 5; 6; 7] # append [2; 4; 6] [8; 10];; - : int list = [2; 4; 6; 8; 10] let rec append l1 l2 =

49 예제 2: 리스트뒤집기 (reverse) val reverse : a list -> a list = <fun> # reverse [1; 2; 3];; - : int list = [3; 2; 1] # reverse ["C"; "Java"; "OCaml"];; - : string list = ["OCaml"; "Java"; "C"] let rec reverse l =

50 예제 3: n 번째원소찾기 (nth-element) # nth [1;2;3] 0;; - : int = 1 # nth [1;2;3] 1;; - : int = 2 # nth [1;2;3] 2;; - : int = 3 # nth [1;2;3] 3;; Exception: Failure "list is too short". let rec nth l n = match l with [] -> raise (Failure "list is too short") hd::tl -> (*... *)

51 예제 4: 첫번째원소지우기 (remove-first) # remove_first 2 [1; 2; 3];; - : int list = [1; 3] # remove_first 2 [1; 2; 3; 2];; - : int list = [1; 3; 2] # remove_first 4 [1;2;3];; - : int list = [1; 2; 3] # remove_first [1; 2] [[1; 2; 3]; [1; 2]; [2; 3]];; - : int list list = [[1; 2; 3]; [2; 3]] let rec remove_first a l =

52 예제 5: 정렬된리스트에원소삽입 (insert) # insert 2 [1;3];; - : int list = [1; 2; 3] # insert 1 [2;3];; - : int list = [1; 2; 3] # insert 3 [1;2];; - : int list = [1; 2; 3] # insert 4 [];; - : int list = [4] let rec insert a l =

53 예제 6: 삽입정렬 (insertion sort) let rec sort l =

54 예제 6: 삽입정렬 (insertion sort) let rec sort l = cf) Compare with C-style non-recursive version: for (c = 1 ; c <= n - 1; c++) { d = c; while ( d > 0 && array[d] < array[d-1]) { t = array[d]; } } array[d] array[d-1] = t; d--; = array[d-1];

55 cf) 명령형 vs. 함수형프로그래밍 Imperative programming focuses on describing how to accomplish the given task: int factorial (int n) { int i; int r = 1; for (i = 0; i < n; i++) r = r * i; return r; } Imperative languages encourage to use statements and loops. Functional programming focuses on describing what the program must accomplish: let rec factorial n = if n = 0 then 1 else n * factorial (n-1) Functional languages encourage to use expressions and recursion.

56 cf) 명령형 vs. 함수형프로그래밍 함수형프로그래밍 높은추상화수준에서프로그래밍 견고한소프트웨어를작성하기쉬움 소프트웨어의실행성질을분석하기쉬움명령형프로그래밍 낮은추상화수준에서프로그래밍 견고한소프트웨어를작성하기어려움 소프트웨어의실행성질을분석하기어려움

57 cf) 오해 : 재귀함수는비싸다? In C and Java, we are encouraged to avoid recursion because function calls consume additional memory. void f() { f(); } /* stack overflow */ This is not true in functional languages. The same program in ML iterates forever: let rec f () = f () 단순히함수가재귀적으로정의되었다고계산과정이비싼것이아님.

58 Tail-Recursive Functions More precisely, tail-recursive functions are not expensive in ML. A recursive call is a tail call if there is nothing to do after the function returns. let rec last l = match l with [a] -> a _::tl -> last tl let rec factorial a = if a = 1 then 1 else a * factorial (a - 1) Languages like ML, Scheme, Scala, and Haskell do tail-call optimization, so that tail-recursive calls do not consume additional amount of memory.

59 cf) Transforming to Tail-Recursive Functions Non-tail-recursive factorial: let rec factorial a = if a = 1 then 1 else a * factorial (a - 1) Tail-recursive version: let rec fact product counter maxcounter = if counter > maxcounter then product else fact (product * counter) (counter + 1) maxcounter let factorial n = fact 1 1 n

60 연습문제 1: range 두수 n, m (n m) 을받아서 n 이상 m 이하의수로구성된리스트를반환하는함수 range 를작성하시오 : range : int -> int -> int list 예를들어, range 3 7 는 [3;4;5;6;7] 를계산한다.

61 연습문제 2: concat 리스트의리스트를받아서모든원소를포함하는하나의리스트를반환하는함수 concat 을작성하시오 : 예를들어, concat: a list list -> a list concat [[1;2];[3;4;5]] = [1;2;3;4;5]

62 연습문제 3: zipper 두리스트 a 와 b 를순차적으로결합하는함수 zipper 를작성하시오 : zipper: int list -> int list -> int list 순차적인결합이란리스트 a 의 i 번째원소가리스트 b 의 i 번째원소앞에오는것을의미한다. 짝이맞지않는원소들은뒤에순서대로붙인다. # zipper [1;3;5] [2;4;6];; - : int list = [1; 2; 3; 4; 5; 6] # zipper [1;3] [2;4;6;8];; - : int list = [1; 2; 3; 4; 6; 8] # zipper [1;3;5;7] [2;4];; - : int list = [1; 2; 3; 4; 5; 7]

63 연습문제 4: unzip 두원소를가지는튜플의리스트를두리스트로분해하는함수 unzip 을작성하시오 : 예를들어, unzip: ( a * b) list -> a list * b list unzip [(1,"one");(2,"two");(3,"three")] 은 ([1;2;3],["one";"two";"three"]) 을계산한다.

64 연습문제 5: drop 리스트 l 과정수 n 을받아서 l 의첫 n 개원소를제외한나머지리스트를구하는함수 drop 을작성하시오 : 예를들어, drop : a list -> int -> a list drop [1;2;3;4;5] 2 = [3; 4; 5] drop [1;2] 3 = [] drop ["C"; "Java"; "OCaml"] 2 = ["OCaml"]

65 고차함수

66 고차함수 (Higher-Order Functions) 다른함수를인자로받거나리턴하는함수 높은추상화 (abstraction) 수준에서프로그램을작성하게함 간결하고재활용가능한코드를작성하는데있어서필수

67 추상화 (Abstraction) 복잡한개념에이름을붙여서속내용을모른채사용할수있도록하는장치 좋은프로그래밍언어는강력한추상화기법을제공 ex) 을계산하는프로그램을작성하는방법 : 2*2*2 + 3*3*3 + 4*4*4 let cube n = n * n * n in cube 2 + cube 3 + cube 4 모든프로그래밍언어는추상화도구로변수와함수를제공 변수 : 반복적으로사용하는값에붙인이름 ( 일차 ) 함수 : 반복적으로사용하는연산에붙인이름 고차함수 : 반복되는프로그래밍패턴에붙인이름

68 List.map Three similar functions: let rec inc_all l = match l with [] -> [] hd::tl -> (hd+1)::(inc_all tl) let rec square_all l = match l with [] -> [] hd::tl -> (hd*hd)::(square_all tl) let rec cube_all l = match l with [] -> [] hd::tl -> (hd*hd*hd)::(cube_all tl)

69 List.map The code pattern can be captured by the higher-order function map: let rec map f l = match l with [] -> [] hd::tl -> (f hd)::(map f tl) With map, the functions can be defined as follows: let inc x = x + 1 let inc_all l = map inc l let square x = x * x let square_all l = map square l let cube x = x * x * x let cube_all l = map cube l Or, using nameless functions: let inc_all l = map (fun x -> x + 1) l let square_all l = map (fun x -> x * x) l let cub_all l = map (fun x -> x * x * x) l

70 퀴즈 1. map 의타입은? 2. map (fun x mod 2 = 1) [1;2;3;4] 의값은?

71 List.filter let rec even l = match l with [] -> [] hd::tl -> if hd mod 2 = 0 then hd::(even tl) else even tl let rec greater_than_five l = match l with [] -> [] hd::tl -> if hd > 5 then hd::(greater_than_five tl) else greater_than_five tl

72 List.filter filter : ( a -> bool) -> a list -> a list even = filter (fun x -> x mod 2 = 0) greater than five = filter (fun x -> x > 5)

73 List.fold right Two similar functions: let rec sum l = match l with [] -> 0 hd::tl -> hd + (sum tl) let rec prod l = match l with [] -> 1 hd::tl -> hd * (prod tl) # sum [1; 2; 3; 4];; - : int = 10 # prod [1; 2; 3; 4];; - : int = 24

74 List.fold right The code pattern can be captured by the higher-oder function fold: let rec fold_right f l a = match l with [] -> a hd::tl -> f hd (fold_right f tl a) let sum lst = fold_right (fun x y -> x + y) lst 0 let prod lst = fold_right (fun x y -> x * y) lst 1

75 fold right vs. fold left let rec fold_right f l a = match l with [] -> a hd::tl -> f hd (fold_right f tl a) let rec fold_left f a l = match l with [] -> a hd::tl -> fold_left f (f a hd) tl

76 차이점 순서 fold right 은리스트를오른쪽에서왼쪽으로 : fold right f [x;y;z] init = f x (f y (f z init)) fold left 는리스트를왼쪽에서오른쪽으로 : 타입 fold left f init [x;y;z] = f (f (f init x) y) z 결합법칙이성립하지않는 f 에대해서결과가다를수있음 fold_right : ( a -> b -> b) -> a list -> b -> b fold_left : ( a -> b -> a) -> a -> b list -> a fold left 는끝재귀호출 (tail-recursion)

77 예제 let rec length l = match l with [] -> 0 hd::tl -> 1 + length tl let rec reverse l = match l with [] -> [] hd::tl -> (reverse [hd] let rec is_all_pos l = match l with [] -> true hd::tl -> (hd > 0) && (is_all_pos tl) map f l = filter f l =

78 연습문제 1 고차함수 sigma를작성하시오 : sigma : (int -> int) -> int -> int -> int sigma f a b는다음을계산한다. b f (i). i=a 예를들어, 의값은 55 이고, sigma (fun x -> x) 1 10 는 140 을계산한다. sigma (fun x -> x*x) 1 7

79 연습문제 2 fold right 을이용하여고차함수 all 을작성하시오 : all : ( a -> bool) -> a list -> bool all p l 은리스트 l 의모든원소들이함수 p 의값을참으로만드는지여부를나타낸다. 예를들어, 는 true 를계산한다. all (fun x -> x > 5) [7;8;9]

80 연습문제 3 fold left 를이용하여정수리스트를숫자로변환하는함수를작성하시오 : lst2int : int list -> int 예를들어, lst2int [1;2;3] 는 123 을계산한다. 리스트의원소들은 0 이상 9 이하의수라고가정한다.

81 함수를반환하는함수의예 함수합성 (composition): Let f and g be two one-argument functions. The composition of f after g is defined to be the function x f (g(x)). In OCaml: let compose f g = fun x -> f(g(x)) What is the value of the expression? ((compose square inc) 6)

82 연습문제 4 함수 f 와인자 a 를받아서 f 를 a 에두번적용한결과를반환하는함수 double 을작성하시오 : 예를들어, # let inc x = x + 1;; val inc : int -> int = <fun> # let mul x = x * 2;; val mul : int -> int = <fun> # (double inc) 1;; - : int = 3 # (double mul) 1;; - : int = 4 아래식의값은? double: ( a -> a) -> a -> a ((double double) inc) 0 (double double) mul 2 ((double (double double)) inc) 5

83 연습문제 5 고차함수 iter 를작성하시오 : iter : int * (int -> int) -> (int -> int) 정의는다음과같다 : iter(n, f ) = f} {{ f}. n n = 0 이면, iter(n, f ) 은항등함수 (identify function) 으로정의한다. n > 0 이면, iter(n, f ) 은 f 를 n 번반복적용하는함수이다. 예를들어, 는 2 n 를계산한다. iter(n, fun x -> 2+x) 0

84 사용자정의타입

85 이미있는타입에새로운이름붙이기 type var = string type vector = float list type matrix = float list list let rec transpose : matrix -> matrix =fun m ->...

86 새로운타입만들기 (Variants) If data elements are finite, just enumerate them, e.g., days : # type days = Mon Tue Wed Thu Fri Sat Sun;; type days = Mon Tue Wed Thu Fri Sat Sun Construct values of the type: # Mon;; - : days = Mon # Tue;; - : days = Tue A function that manipulates the defined data: # let nextday d = match d with Mon -> Tue Tue -> Wed Wed -> Thu Thu -> Fri Fri -> Sa Sat -> Sun Sun -> Mon ;; val nextday : days -> days = <fun> # nextday Mon;; - : days = Tue

87 새로운타입만들기 (Variants) Constructors can be associated with values, e.g., # type shape = Rect of int * int Circle of int;; type shape = Rect of int * int Circle of int Construct values of the type: # Rect (2,3);; - : shape = Rect (2, 3) # Circle 5;; - : shape = Circle 5 A function that manipulates the data: # let area s = match s with Rect (w,h) -> w * h Circle r -> r * r * 3;; val area : shape -> int = <fun> # area (Rect (2,3));; - : int = 6 # area (Circle 5);; - : int = 75

88 새로운타입만들기 (Variants) Inductive data types, e.g., # type mylist = Nil List of int * mylist;; type mylist = Nil List of int * mylist Construct values of the type: # Nil;; - : mylist = Nil # List (1, Nil);; - : mylist = List (1, Nil) # List (1, List (2, Nil));; - : mylist = List (1, List (2, Nil)) A function that manipulates the data: # let rec mylength l = match l with Nil -> 0 List (_,l ) -> 1 + mylength l ;; val mylength : mylist -> int = <fun> # mylength (List (1, List (2, Nil)));; - : int = 2

89 새로운타입만들기 (Parameterized Variants) 임의의타입을담을수있는리스트를만드려면? e.g., lists of ints, lists of strings, lists of lists of ints, etc 다른타입을인자로가지는타입을정의가능 : # type a mylist = Nil Cons of a * a mylist;; type a mylist = Nil Cons of a * a mylist # let l1 = Cons (3, Nil) ;; val l1 : int mylist = Cons (3, Nil) # let l2 = Cons ("three", Nil);; val l2 : string mylist = Cons ("three", Nil) # let rec length l = match l with Nil -> 0 Cons (_,t) -> 1 + length t;; val length : a mylist -> int = <fun> mylist: 다른타입을인자로받아서다른타입을만들어내는타입생성자 (type constructor) int mylist, float mylist, (int * float) mylist, etc

90 연습문제 1: 이진나무 (ver. 1) 이진나무 (binary tree) 는다음과같이정의할수있다 : type btree = Empty Node of int * btree * btree 예를들어, let t1 = Node (1, Empty, Empty) let t2 = Node (1, Node (2, Empty, Empty), Node (3, Empty,Empty)) 이진나무에서주어진원소가존재하는지여부를반환하는함수 mem 을작성하시오 : mem: int -> btree -> bool 예를들어, 는 true 이고, 는 false 이다. mem 1 t1 mem 4 t2

91 연습문제 2: 이진나무 (ver. 2) 이진나무를다음과같이정의하자. type btree = Leaf of int Left of btree Right of btree LeftRight of btree * btree 예를들어, Left (LeftRight (Leaf 1, Leaf 2)) 이진나무의왼쪽, 오른쪽자식을재귀적으로모두교환하는함수 mirror 를작성하시오 : 예를들어, mirror : btree -> btree mirror (Left (LeftRight (Leaf 1, Leaf 2))) 는 Right (LeftRight (Leaf 2, Leaf 1)) 를계산한다.

92 연습문제 3: 계산기 (ver. 1) type exp = Const of int Minus of exp Plus of exp * exp Mult of exp * exp 위산술식의값을계산하는함수 를작성하시오. 예를들어, 는 3 을계산한다. calc: exp -> int calc (Plus (Const 1, Const 2))

93 연습문제 4: 계산기 (ver. 2) type exp = X INT of int ADD of exp * exp SUB of exp * exp MUL of exp * exp DIV of exp * exp SIGMA of exp * exp * exp 위식에대한계산기를작성하시오 : calculator : exp -> int 예를들어, 는다음과같이표현되며 10 x=1 (x x 1) SIGMA(INT 1, INT 10, SUB(MUL(X, X), INT 1)) 그계산결과는 375 이다.

94 리뷰 OCaml 기본구성 : 식, 변수, 함수, 유효범위 리스트와재귀함수 고차함수 사용자정의타입 감사합니다!

OCaml

OCaml OCaml 2009.. (khheo@ropas.snu.ac.kr) 1 ML 2 ML OCaml INRIA, France SML Bell lab. & Princeton, USA nml SNU/KAIST, KOREA 3 4 (let) (* ex1.ml *) let a = 10 let add x y = x + y (* ex2.ml *) let sumofsquare

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Programming Languages 모듈과펑터 2016 년봄학기 손시운 (ssw5176@kangwon.ac.kr) 담당교수 : 임현승교수님 모듈 (module) 관련있는정의 ( 변수또는함수 ) 를하나로묶은패키지 예약어 module과 struct end를사용하여정의 아래는모듈의예시 ( 우선순위큐, priority queue) # module PrioQueue

More information

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 SNU 4190.210 프로그래밍 원리 (Principles of Programming) Part III Prof. Kwangkeun Yi 차례 1 값중심 vs 물건중심프로그래밍 (applicative vs imperative programming) 2 프로그램의이해 : 환경과메모리 (environment & memory) 다음 1 값중심 vs 물건중심프로그래밍

More information

HW5 Exercise 1 (60pts) M interpreter with a simple type system M. M. M.., M (simple type system). M, M. M., M.

HW5 Exercise 1 (60pts) M interpreter with a simple type system M. M. M.., M (simple type system). M, M. M., M. 오늘할것 5 6 HW5 Exercise 1 (60pts) M interpreter with a simple type system M. M. M.., M (simple type system). M, M. M., M. Review: 5-2 7 7 17 5 4 3 4 OR 0 2 1 2 ~20 ~40 ~60 ~80 ~100 M 언어 e ::= const constant

More information

chap 5: Trees

chap 5: Trees 5. Threaded Binary Tree 기본개념 n 개의노드를갖는이진트리에는 2n 개의링크가존재 2n 개의링크중에 n + 1 개의링크값은 null Null 링크를다른노드에대한포인터로대체 Threads Thread 의이용 ptr left_child = NULL 일경우, ptr left_child 를 ptr 의 inorder predecessor 를가리키도록변경

More information

기본자료형만으로이루어진인자를받아서함수를결과값으로반환하는고차함수 기본자료형과함수를인자와결과값에모두이용하는고차함수 다음절에서는여러가지예를통해서고차함수가어떤경우에유용한지를설명한다. 2 고차함수의 예??장에서대상체만바뀌고중간과정은동일한계산이반복될때함수를이용하면전체연산식을간 단

기본자료형만으로이루어진인자를받아서함수를결과값으로반환하는고차함수 기본자료형과함수를인자와결과값에모두이용하는고차함수 다음절에서는여러가지예를통해서고차함수가어떤경우에유용한지를설명한다. 2 고차함수의 예??장에서대상체만바뀌고중간과정은동일한계산이반복될때함수를이용하면전체연산식을간 단 EECS-101 전자계산입문 고차함수 박성우 2008년5월 29일 지금까지정수나부동소수와같은기본적인자료형의조합을인자로받고결과값으로반환하는 함수에대해서배웠다. 이번강의에서는함수자체를다른함수의인자로이용하거나결과값으로 이용하는 방법을 배운다. 1 고차함수의 의미 계산은무엇을어떻게처리하여결과값을얻는지설명하는것으로이루어진다. 여기서 무엇 과 결 과값 은계산의대상체로서정수나부동소수와같은기본자료형의조합으로표현하며,

More information

chap x: G입력

chap x: G입력 재귀알고리즘 (Recursive Algorithms) 재귀알고리즘의특징 문제자체가재귀적일경우적합 ( 예 : 피보나치수열 ) 이해하기가용이하나, 비효율적일수있음 재귀알고리즘을작성하는방법 재귀호출을종료하는경계조건을설정 각단계마다경계조건에접근하도록알고리즘의재귀호출 재귀알고리즘의두가지예 이진검색 순열 (Permutations) 1 장. 기본개념 (Page 19) 이진검색의재귀알고리즘

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 2... ( ). ( ). @ vs. logic data method variable behavior attribute method field Flow (Type), ( ) member @ () : C program Method A ( ) Method B ( ) Method C () program : Java, C++, C# data @ Program

More information

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf(hihi\n); } warning: conflicting types for functiona 이름 : 학번 : A. True or False: 각각항목마다 True 인지 False 인지적으세요. 1. (Python:) randint 함수를사용하려면, random 모듈을 import 해야한다. 2. (Python:) '' (single quote) 는한글자를표현할때, (double quote) 는문자열을표현할때사용한다. B. 다음에러를수정하는방법을적으세요.

More information

슬라이드 1

슬라이드 1 Pairwise Tool & Pairwise Test NuSRS 200511305 김성규 200511306 김성훈 200614164 김효석 200611124 유성배 200518036 곡진화 2 PICT Pairwise Tool - PICT Microsoft 의 Command-line 기반의 Free Software www.pairwise.org 에서다운로드후설치

More information

1

1 1 1....6 1.1...6 2. Java Architecture...7 2.1 2SDK(Software Development Kit)...8 2.2 JRE(Java Runtime Environment)...9 2.3 (Java Virtual Machine, JVM)...10 2.4 JVM...11 2.5 (runtime)jvm...12 2.5.1 2.5.2

More information

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 SNU 4190.210 프로그래밍 원리 (Principles of Programming) Part IV Prof. Kwangkeun Yi 차례 1 안전하게프로그래밍하기 : 손수 vs 자동 2 맞는지확인하기쉽게프로그램하기 3 대형프로그래밍을위한기술 : 모듈프로그래밍 다음 1 안전하게프로그래밍하기 : 손수 vs 자동 2 맞는지확인하기쉽게프로그램하기 3 대형프로그래밍을위한기술

More information

Microsoft PowerPoint Predicates and Quantifiers.ppt

Microsoft PowerPoint Predicates and Quantifiers.ppt 이산수학 () 1.3 술어와한정기호 (Predicates and Quantifiers) 2006 년봄학기 문양세강원대학교컴퓨터과학과 술어 (Predicate), 명제함수 (Propositional Function) x is greater than 3. 변수 (variable) = x 술어 (predicate) = P 명제함수 (propositional function)

More information

Homework 2 SNU , Fall 2015 Kwangkeun Yi due: 9/30, 24:00 Exercise 1 (10pts) k- 친수 일반적으로 k 진수 (k > 1) 는다음과같이표현한다. d 0 d n 여기서 d i {0,, k 1}. 그리

Homework 2 SNU , Fall 2015 Kwangkeun Yi due: 9/30, 24:00 Exercise 1 (10pts) k- 친수 일반적으로 k 진수 (k > 1) 는다음과같이표현한다. d 0 d n 여기서 d i {0,, k 1}. 그리 Homework 2 SNU 4190.310, Fall 2015 Kwangkeun Yi due: 9/30, 24:00 Exercise 1 (10pts) k- 친수 일반적으로 k 진수 (k > 1) 는다음과같이표현한다. d 0 d n 여기서 d i {0,, k 1}. 그리고 d 0 d n 은크기가 d 0 k 0 + + d n k n 인정수를표현한다. 이것을살짝확장해서

More information

02 C h a p t e r Java

02 C h a p t e r Java 02 C h a p t e r Java Bioinformatics in J a va,, 2 1,,,, C++, Python, (Java),,, (http://wwwbiojavaorg),, 13, 3D GUI,,, (Java programming language) (Sun Microsystems) 1995 1990 (green project) TV 22 CHAPTER

More information

Microsoft PowerPoint - ch10 - 이진트리, AVL 트리, 트리 응용 pm0600

Microsoft PowerPoint - ch10 - 이진트리, AVL 트리, 트리 응용 pm0600 균형이진탐색트리 -VL Tree delson, Velskii, Landis에의해 1962년에제안됨 VL trees are balanced n VL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at

More information

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt 변수와상수 1 변수란무엇인가? 변수 : 정보 (data) 를저장하는컴퓨터내의특정위치 ( 임시저장공간 ) 메모리, register 메모리주소 101 번지 102 번지 변수의크기에따라 주로 byte 단위 메모리 2 기본적인변수형및변수의크기 변수의크기 해당컴퓨터에서는항상일정 컴퓨터마다다를수있음 short

More information

....201506

....201506 TFT 2015 06 7 12 % 5 13 % 6 46 % 3 % 8 % 14 % 33% 2 % 22 % 23 % 29 % 50 % 18 % 5 28 % 8 1 % 4 % 22 % 7 % 26 % 41 % 5 % 5 % 10 % 6 % 10 % 8 % 12 % 12 % 50 % 23 % 10 % 5 22 % 15 % % 3 % 3 % QUIZ mind tip

More information

OCW_C언어 기초

OCW_C언어 기초 초보프로그래머를위한 C 언어기초 4 장 : 연산자 2012 년 이은주 학습목표 수식의개념과연산자및피연산자에대한학습 C 의알아보기 연산자의우선순위와결합방향에대하여알아보기 2 목차 연산자의기본개념 수식 연산자와피연산자 산술연산자 / 증감연산자 관계연산자 / 논리연산자 비트연산자 / 대입연산자연산자의우선순위와결합방향 조건연산자 / 형변환연산자 연산자의우선순위 연산자의결합방향

More information

Microsoft PowerPoint - ch07 - 포인터 pm0415

Microsoft PowerPoint - ch07 - 포인터 pm0415 2015-1 프로그래밍언어 7. 포인터 (Pointer), 동적메모리할당 2015 년 4 월 4 일 교수김영탁 영남대학교공과대학정보통신공학과 (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr) Outline 포인터 (pointer) 란? 간접참조연산자

More information

Exercise (10pts) k-친수 일반적으로 k진수(k > 1)는 다음과 같이 표현한다. d0 dn 여기서 di {0,, k 1}. 그리고 d0 dn 은 크기가 d0 k dn k n 인 정수를 표현한다. 이것을 살짝 확장해서 k친수 를 다음과 같이 정의

Exercise (10pts) k-친수 일반적으로 k진수(k > 1)는 다음과 같이 표현한다. d0 dn 여기서 di {0,, k 1}. 그리고 d0 dn 은 크기가 d0 k dn k n 인 정수를 표현한다. 이것을 살짝 확장해서 k친수 를 다음과 같이 정의 Homework SNU 4190.310, Fall 017 Kwangkeun Yi due: 9/8, 4:00 Exercise 1 (10pts) 참거짓 Propositional Logic 식들 (formula) 을다음과같이정의했습니다 : type formula = TRUE FALSE NOT of formula ANDALSO of formula * formula

More information

금오공대 컴퓨터공학전공 강의자료

금오공대 컴퓨터공학전공 강의자료 C 프로그래밍프로젝트 Chap 14. 포인터와함수에대한이해 2013.10.09. 오병우 컴퓨터공학과 14-1 함수의인자로배열전달 기본적인인자의전달방식 값의복사에의한전달 val 10 a 10 11 Department of Computer Engineering 2 14-1 함수의인자로배열전달 배열의함수인자전달방식 배열이름 ( 배열주소, 포인터 ) 에의한전달 #include

More information

ThisJava ..

ThisJava .. 자바언어에정확한타입을추가한 ThisJava 소개 나현익, 류석영 프로그래밍언어연구실 KAIST 2014 년 1 월 14 일 나현익, 류석영 자바언어에정확한타입을추가한 ThisJava 소개 1/29 APLAS 2013 나현익, 류석영 자바 언어에 정확한 타입을 추가한 ThisJava 소개 2/29 실제로부딪힌문제 자바스크립트프로그램분석을위한요약도메인 나현익,

More information

예제 1.1 ( 관계연산자 ) >> A=1:9, B=9-A A = B = >> tf = A>4 % 4 보다큰 A 의원소들을찾을경우 tf = >> tf = (A==B) % A

예제 1.1 ( 관계연산자 ) >> A=1:9, B=9-A A = B = >> tf = A>4 % 4 보다큰 A 의원소들을찾을경우 tf = >> tf = (A==B) % A 예제 1.1 ( 관계연산자 ) >> A=1:9, B=9-A A = 1 2 3 4 5 6 7 8 9 B = 8 7 6 5 4 3 2 1 0 >> tf = A>4 % 4 보다큰 A 의원소들을찾을경우 tf = 0 0 0 0 1 1 1 1 1 >> tf = (A==B) % A 의원소와 B 의원소가똑같은경우를찾을때 tf = 0 0 0 0 0 0 0 0 0 >> tf

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 3 if, if else, if else if, switch case for, while, do while break, continue : System.in, args, JOptionPane for (,, ) @ vs. logic data method variable Data Data Flow (Type), ( ) @ Member field

More information

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100 2015-1 프로그래밍언어 9. 연결형리스트, Stack, Queue 2015 년 5 월 4 일 교수김영탁 영남대학교공과대학정보통신공학과 (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr) 연결리스트 (Linked List) 연결리스트연산 Stack

More information

SIGPLwinterschool2012

SIGPLwinterschool2012 1994 1992 2001 2008 2002 Semantics Engineering with PLT Redex Matthias Felleisen, Robert Bruce Findler and Matthew Flatt 2009 Text David A. Schmidt EXPRESSION E ::= N ( E1 O E2 ) OPERATOR O ::=

More information

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

Microsoft PowerPoint 자바-기본문법(Ch2).pptx 자바기본문법 1. 기본사항 2. 자료형 3. 변수와상수 4. 연산자 1 주석 (Comments) 이해를돕기위한설명문 종류 // /* */ /** */ 활용예 javadoc HelloApplication.java 2 주석 (Comments) /* File name: HelloApplication.java Created by: Jung Created on: March

More information

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 ±×to0.

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 ±×to0. 차례 SNU 4190.210 프로그래밍원리 (Principles of Programming) Part II Prof. Kwangkeun Yi 다음 데이타구현하기 (data implementation) 새로운타입의데이타 / 값구현하기 기억하는가 : 타입들 (types) τ ::= ι primitive type τ τ pair(product) type τ + τ

More information

Homework 1 SNU , Fall 2012 Kwangkeun Yi Due: 9/14, 24:00 Exercise 1 리스트합 큰순서대로 (descending order) 나열된정수리스트두개를받아서하나의 순서리스트로만드는함수 merge: int lis

Homework 1 SNU , Fall 2012 Kwangkeun Yi Due: 9/14, 24:00 Exercise 1 리스트합 큰순서대로 (descending order) 나열된정수리스트두개를받아서하나의 순서리스트로만드는함수 merge: int lis Homework 1 SNU 4190.310, Fall 2012 Kwangkeun Yi Due: 9/14, 24:00 Exercise 1 리스트합 큰순서대로 (descending order) 나열된정수리스트두개를받아서하나의 순서리스트로만드는함수 merge: int list * int list -> int list 를정의하세요. 리스트에는같은정수가반복해서들어있지않습니다.

More information

λx.x (λz.λx.x z) (λx.x)(λz.(λx.x)z) (λz.(λx.x) z) Call-by Name. Normal Order. (λz.z)

λx.x (λz.λx.x z) (λx.x)(λz.(λx.x)z) (λz.(λx.x) z) Call-by Name. Normal Order. (λz.z) λx.x (λz.λx.x z) (λx.x)(λz.(λx.x)z) (λz.(λx.x) z) Call-by Name. Normal Order. (λz.z) Simple Type System - - 1+malloc(), {x:=1,y:=2}+2,... (stuck) { } { } ADD σ,m e 1 n 1,M σ,m e 1 σ,m e 2 n 2,M + e 2 n

More information

Microsoft PowerPoint - chap-03.pptx

Microsoft PowerPoint - chap-03.pptx 쉽게풀어쓴 C 언어 Express 제 3 장 C 프로그램구성요소 컴퓨터프로그래밍기초 이번장에서학습할내용 * 주석 * 변수, 상수 * 함수 * 문장 * 출력함수 printf() * 입력함수 scanf() * 산술연산 * 대입연산 이번장에서는 C프로그램을이루는구성요소들을살펴봅니다. 컴퓨터프로그래밍기초 2 일반적인프로그램의형태 데이터를받아서 ( 입력단계 ), 데이터를처리한후에

More information

설계란 무엇인가?

설계란 무엇인가? 금오공과대학교 C++ 프로그래밍 jhhwang@kumoh.ac.kr 컴퓨터공학과 황준하 6 강. 함수와배열, 포인터, 참조목차 함수와포인터 주소값의매개변수전달 주소의반환 함수와배열 배열의매개변수전달 함수와참조 참조에의한매개변수전달 참조의반환 프로그래밍연습 1 /15 6 강. 함수와배열, 포인터, 참조함수와포인터 C++ 매개변수전달방법 값에의한전달 : 변수값,

More information

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2 비트연산자 1 1 비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2 진수법! 2, 10, 16, 8! 2 : 0~1 ( )! 10 : 0~9 ( )! 16 : 0~9, 9 a, b,

More information

2002년 2학기 자료구조

2002년 2학기 자료구조 자료구조 (Data Structures) Chapter 1 Basic Concepts Overview : Data (1) Data vs Information (2) Data Linear list( 선형리스트 ) - Sequential list : - Linked list : Nonlinear list( 비선형리스트 ) - Tree : - Graph : (3)

More information

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 ±×to0.

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 ±×to0. 프로그래밍 원리 (Principles of Programming) Part II Prof. Kwangkeun Yi 차례 1 데이타구현하기 (data implementation) 2 데이터속구현감추기 (data abstraction) 3 여러구현동시지원하기 (multiple implemenations) 4 각계층별로속구현감추기 (data abstraction

More information

제4장 기본 의미구조 (Basic Semantics)

제4장  기본 의미구조 (Basic Semantics) 제 4 장블록및유효범위 Reading Chap. 5 숙대창병모 1 4.1 변수선언및유효범위 숙대창병모 2 변수선언과유효범위 변수선언 Declaration before Use! 대부분의언어에서변수는사용전에먼저선언해야한다. 변수의유효범위 (scope) 선언된변수가유효한 ( 사용될수있는 ) 프로그램내의범위 / 영역 변수이름뿐아니라함수등다른이름도생각해야한다. 정적유효범위

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 제 3 장함수와문자열 1. 함수의기본적인개념을이해한다. 2. 인수와매개변수의개념을이해한다. 3. 함수의인수전달방법 2가지를이해한다 4. 중복함수를이해한다. 5. 디폴트매개변수를이해한다. 6. 문자열의구성을이해한다. 7. string 클래스의사용법을익힌다. 이번장에서만들어볼프로그램 함수란? 함수선언 함수호출 예제 #include using

More information

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 ±×to0.

SNU =10100 =minusby by1000 ÇÁto0.03exÇÁto0.03exÇÁ=10100 =minusby by1000 ·Îto0.03ex·Îto0.03ex·Î=10100 =minusby by1000 ±×to0. 프로그래밍 원리 (Principles of Programming) Part IV Prof. Kwangkeun Yi 차례 1 안전하게프로그래밍하기 : 손수 vs 자동 2 맞는지확인하기쉽게프로그램하기 3 대형프로그래밍을위한기술 : 모듈프로그래밍 다음 1 안전하게프로그래밍하기 : 손수 vs 자동 2 맞는지확인하기쉽게프로그램하기 3 대형프로그래밍을위한기술 : 모듈프로그래밍

More information

03장.스택.key

03장.스택.key ---------------- DATA STRUCTURES USING C ---------------- 03CHAPTER 1 ? (stack): (LIFO:Last-In First-Out) 2 : top : ( index -1 ),,, 3 : ( ) ( ) -> ->. ->.... 4 Stack ADT : (LIFO) : init():. is_empty():

More information

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Function) 1. 함수의개념 입력에대해적절한출력을발생시켜주는것 내가 ( 프로그래머 ) 작성한명령문을연산, 처리, 실행해주는부분 ( 모듈 ) 자체적으로실행되지않으며,

More information

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning C Programming Practice (II) Contents 배열 문자와문자열 구조체 포인터와메모리관리 구조체 2/17 배열 (Array) (1/2) 배열 동일한자료형을가지고있으며같은이름으로참조되는변수들의집합 배열의크기는반드시상수이어야한다. type var_name[size]; 예 ) int myarray[5] 배열의원소는원소의번호를 0 부터시작하는색인을사용

More information

C++-¿Ïº®Çؼ³10Àå

C++-¿Ïº®Çؼ³10Àå C C++. (preprocessor directives), C C++ C/C++... C++, C. C++ C. C C++. C,, C++, C++., C++.,.. #define #elif #else #error #if #itdef #ifndef #include #line #pragma #undef #.,.,. #include #include

More information

17장 클래스와 메소드

17장 클래스와 메소드 17 장클래스와메소드 박창이 서울시립대학교통계학과 박창이 ( 서울시립대학교통계학과 ) 17 장클래스와메소드 1 / 18 학습내용 객체지향특징들객체출력 init 메소드 str 메소드연산자재정의타입기반의버전다형성 (polymorphism) 박창이 ( 서울시립대학교통계학과 ) 17 장클래스와메소드 2 / 18 객체지향특징들 객체지향프로그래밍의특징 프로그램은객체와함수정의로구성되며대부분의계산은객체에대한연산으로표현됨객체의정의는

More information

학습목표 함수프로시저, 서브프로시저의의미를안다. 매개변수전달방식을학습한다. 함수를이용한프로그래밍한다. 2

학습목표 함수프로시저, 서브프로시저의의미를안다. 매개변수전달방식을학습한다. 함수를이용한프로그래밍한다. 2 학습목표 함수프로시저, 서브프로시저의의미를안다. 매개변수전달방식을학습한다. 함수를이용한프로그래밍한다. 2 6.1 함수프로시저 6.2 서브프로시저 6.3 매개변수의전달방식 6.4 함수를이용한프로그래밍 3 프로시저 (Procedure) 프로시저 (Procedure) 란무엇인가? 논리적으로묶여있는하나의처리단위 내장프로시저 이벤트프로시저, 속성프로시저, 메서드, 비주얼베이직내장함수등

More information

11장 포인터

11장 포인터 누구나즐기는 C 언어콘서트 제 9 장포인터 이번장에서학습할내용 포인터이란? 변수의주소 포인터의선언 간접참조연산자 포인터연산 포인터와배열 포인터와함수 이번장에서는포인터의기초적인지식을학습한다. 포인터란? 포인터 (pointer): 주소를가지고있는변수 메모리의구조 변수는메모리에저장된다. 메모리는바이트단위로액세스된다. 첫번째바이트의주소는 0, 두번째바이트는 1, 변수와메모리

More information

<C7E0BAB9C0AFBCBA5F323031365F30365F322E696E6464>

<C7E0BAB9C0AFBCBA5F323031365F30365F322E696E6464> 2016.06 www.yuseong.go.kr Vol.125 2016.06 www.yuseong.go.kr Vol.125 04 06 08 10 12 14 18 20 21 22 23 24 26 28 29 30 04 06 2016.06 www.yuseong.go.kr Vol.125 14 12 23 4 2016. 06 5 6 2016. 06 7 모이자~ 8 2016.

More information

chap01_time_complexity.key

chap01_time_complexity.key 1 : (resource),,, 2 (time complexity),,, (worst-case analysis) (average-case analysis) 3 (Asymptotic) n growth rate Θ-, Ο- ( ) 4 : n data, n/2. int sample( int data[], int n ) { int k = n/2 ; return data[k]

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Lecture 02 프로그램구조및문법 Kwang-Man Ko kkmam@sangji.ac.kr, compiler.sangji.ac.kr Department of Computer Engineering Sang Ji University 2018 자바프로그램기본구조 Hello 프로그램구조 sec01/hello.java 2/40 자바프로그램기본구조 Hello 프로그램구조

More information

Columns 8 through while expression {commands} 예제 1.2 (While 반복문의이용 ) >> num=0

Columns 8 through while expression {commands} 예제 1.2 (While 반복문의이용 ) >> num=0 for loop array {commands} 예제 1.1 (For 반복변수의이용 ) >> data=[3 9 45 6; 7 16-1 5] data = 3 9 45 6 7 16-1 5 >> for n=data x=n(1)-n(2) -4-7 46 1 >> for n=1:10 x(n)=sin(n*pi/10); n=10; >> x Columns 1 through 7

More information

Microsoft Word - FunctionCall

Microsoft Word - FunctionCall Function all Mechanism /* Simple Program */ #define get_int() IN KEYOARD #define put_int(val) LD A val \ OUT MONITOR int add_two(int a, int b) { int tmp; tmp = a+b; return tmp; } local auto variable stack

More information

C++ Programming

C++ Programming C++ Programming 예외처리 Seo, Doo-okok clickseo@gmail.com http://www.clickseo.com 목 차 예외처리 2 예외처리 예외처리 C++ 의예외처리 예외클래스와객체 3 예외처리 예외를처리하지않는프로그램 int main() int a, b; cout > a >> b; cout

More information

Modern Javascript

Modern Javascript ES6 - Arrow Function Class Template String Destructuring Default, Rest, Spread let, const for..of Promises Module System Map, Set * Generator * Symbol * * https://babeljs.io/ Babel is a JavaScript compiler.

More information

Microsoft PowerPoint - [2009] 02.pptx

Microsoft PowerPoint - [2009] 02.pptx 원시데이터유형과연산 원시데이터유형과연산 원시데이터유형과연산 숫자데이터유형 - 숫자데이터유형 원시데이터유형과연산 표준입출력함수 - printf 문 가장기본적인출력함수. (stdio.h) 문법 ) printf( Test printf. a = %d \n, a); printf( %d, %f, %c \n, a, b, c); #include #include

More information

slide2

slide2 Program P ::= CL CommandList CL ::= C C ; CL Command C ::= L = E while E : CL end print L Expression E ::= N ( E + E ) L &L LefthandSide L ::= I *L Variable I ::= Numeral N ::=

More information

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770> 연습문제해답 5 4 3 2 1 0 함수의반환값 =15 5 4 3 2 1 0 함수의반환값 =95 10 7 4 1-2 함수의반환값 =3 1 2 3 4 5 연습문제해답 1. C 언어에서의배열에대하여다음중맞는것은? (1) 3차원이상의배열은불가능하다. (2) 배열의이름은포인터와같은역할을한다. (3) 배열의인덱스는 1에서부터시작한다. (4) 선언한다음, 실행도중에배열의크기를변경하는것이가능하다.

More information

슬라이드 1

슬라이드 1 Recursion SANGJI University KO Kwangman () 1. 개요 재귀 (recursion) 의정의, 순환 정의하고있는개념자체에대한정의내부에자기자신이포함되어있는경우를의미 알고리즘이나함수가수행도중에자기자신을다시호출하여문제를해결하는기법 정의자체가순환적으로되어있는경우에적합한방법 예제 ) 팩토리얼값구하기 피보나치수열 이항계수 하노이의탑 이진탐색

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 순환알고리즘 C 로쉽게풀어쓴자료구조 순환 (recursion) 수행이끝나기전에자기자신을다시호출하여문제해결 - 직접순환, 간접순환 문제정의가순환적으로되어있는경우에적합한방법 ( 예제 ) 팩토리얼 피보나치수열 n! 1 n * ( n 1)! n n 0 fib( n) 1 fib ( n 2) fib( n 1) 1 ` 2 if if n 0 n 1 otherwise 이항계수

More information

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx #include int main(void) { int num; printf( Please enter an integer "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; } 1 학습목표 을 작성하면서 C 프로그램의

More information

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다. 제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver. 2.0 jbyoo@konkuk.ac.kr http://dslab.konkuk.ac.kr 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다. 이번장에서학습할내용 이중포인터란무엇인가? 포인터배열 함수포인터 다차원배열과포인터 void 포인터 포인터는다양한용도로유용하게활용될수있습니다. 2 이중포인터

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스, 객체, 메소드 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 필드만있는클래스 텔레비젼 2 예제 1. 필드만있는클래스 3 예제 2. 여러개의객체생성하기 4 5 예제 3. 메소드가추가된클래스 public class Television { int channel; // 채널번호 int volume; // 볼륨 boolean

More information

Microsoft PowerPoint - 27.pptx

Microsoft PowerPoint - 27.pptx 이산수학 () n-항관계 (n-ary Relations) 2011년봄학기 강원대학교컴퓨터과학전공문양세 n-ary Relations (n-항관계 ) An n-ary relation R on sets A 1,,A n, written R:A 1,,A n, is a subset R A 1 A n. (A 1,,A n 에대한 n- 항관계 R 은 A 1 A n 의부분집합이다.)

More information

Introduction to Geotechnical Engineering II

Introduction to  Geotechnical Engineering II Fundamentals of Computer System - chapter 9. Functions 민기복 Ki-Bok Min, PhD 서울대학교에너지자원공학과조교수 Assistant Professor, Energy Resources Engineering Last week Chapter 7. C control statements: Branching and Jumps

More information

PL10

PL10 assert(p!=null); *p = 10; assert(0

More information

C# Programming Guide - Types

C# Programming Guide - Types C# Programming Guide - Types 최도경 lifeisforu@wemade.com 이문서는 MSDN 의 Types 를요약하고보충한것입니다. http://msdn.microsoft.com/enus/library/ms173104(v=vs.100).aspx Types, Variables, and Values C# 은 type 에민감한언어이다. 모든

More information

Microsoft PowerPoint - Lesson2.pptx

Microsoft PowerPoint - Lesson2.pptx Computer Engineering g Programming g 2 제 3 장 C 프로그래밍구성요소 Lecturer: JUNBEOM YOO jbyoo@konkuk.ac.kr 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다. 이번장에서학습할내용 * 주석 * 변수, 상수 * 함수 * 문장 * 출력함수 printf() * 입력함수 scanf() *

More information

EECS101 전자계산입문여섯번째숙제 -리스트- (100 점 + 도전문제점수 50점 ) 오진오 제출마감 : 5월 1일 11:59pm 이번숙제에서는수업시간에배웠던리스트에대한기본개념을프로그래밍을통해익혀보고, 리스트를통해가능한문제해결방법에대해서알

EECS101 전자계산입문여섯번째숙제 -리스트- (100 점 + 도전문제점수 50점 ) 오진오 제출마감 : 5월 1일 11:59pm 이번숙제에서는수업시간에배웠던리스트에대한기본개념을프로그래밍을통해익혀보고, 리스트를통해가능한문제해결방법에대해서알 EECS101 전자계산입문여섯번째숙제 -리스트- (100 점 + 도전문제점수 50점 ) 오진오 (kurin@postech) 제출마감 : 5월 1일 11:59pm 이번숙제에서는수업시간에배웠던리스트에대한기본개념을프로그래밍을통해익혀보고, 리스트를통해가능한문제해결방법에대해서알아봅니다. 부정행위에관한규정은 POSTECH 전자컴퓨터공학부학부위원회의 POSTECH 전자컴퓨터공학부부정행위정의

More information

쉽게

쉽게 Power Java 제 4 장자바프로그래밍기초 이번장에서학습할내용 자바프로그램에대한기초사항을학습 자세한내용들은추후에. Hello.java 프로그램 주석 주석 (comment): 프로그램에대한설명을적어넣은것 3 가지타입의주석 클래스 클래스 (class): 객체를만드는설계도 ( 추후에학습 ) 자바프로그램은클래스들로구성된다. 그림 4-1. 자바프로그램의구조 클래스정의

More information

JUNIT 실습및발표

JUNIT 실습및발표 JUNIT 실습및발표 JUNIT 접속 www.junit.org DownLoad JUnit JavaDoc API Document 를참조 JUNIT 4.8.1 다운로드 설치파일 (jar 파일 ) 을다운로드 CLASSPATH 를설정 환경변수에서설정 실행할클래스에서 import JUnit 설치하기 테스트실행주석 @Test Test 를실행할 method 앞에붙임 expected

More information

05-class.key

05-class.key 5 : 2 (method) (public) (private) (interface) 5.1 (Method), (public method) (private method) (constructor), 3 4 5.2 (client). (receiver)., System.out.println("Hello"); (client object) (receiver object)

More information

C 프로그래밊 개요

C 프로그래밊 개요 함수 (2) 2009 년 9 월 24 일 김경중 공지사항 10 월 1 일목요일수업휴강 숙제 #1 마감 : 10 월 6 일화요일 기초 함수를만들어라! 입력 함수 ( 기능수행 ) 반환 사용자정의함수 정의 : 사용자가자신의목적에따라직접작성한함수 함수의원형 (Function Prototype) + 함수의본체 (Function Body) : 함수의원형은함수에대한기본적정보만을포함

More information

Microsoft PowerPoint - C++ 5 .pptx

Microsoft PowerPoint - C++ 5 .pptx C++ 언어프로그래밍 한밭대학교전자. 제어공학과이승호교수 연산자중복 (operator overloading) 이란? 2 1. 연산자중복이란? 1) 기존에미리정의되어있는연산자 (+, -, /, * 등 ) 들을프로그래머의의도에맞도록새롭게정의하여사용할수있도록지원하는기능 2) 연산자를특정한기능을수행하도록재정의하여사용하면여러가지이점을가질수있음 3) 하나의기능이프로그래머의의도에따라바뀌어동작하는다형성

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 4 (Object) (Class) (Instance) (Method) (Constructor) Memory 1 UML 1 @ & 1 (Real World) (Software World) @ &.. () () @ & 2 (Real World) (Software World) OOA/ Modeling Abstraction Instantiation

More information

윈도우즈프로그래밍(1)

윈도우즈프로그래밍(1) 제어문 (2) For~Next 문 윈도우즈프로그래밍 (1) ( 신흥대학교컴퓨터정보계열 ) 2/17 Contents 학습목표 프로그램에서주어진특정문장을부분을일정횟수만큼반복해서실행하는문장으로 For~Next 문등의구조를이해하고활용할수있다. 내용 For~Next 문 다중 For 문 3/17 제어문 - FOR 문 반복문 : 프로그램에서주어진특정문장들을일정한횟수만큼반복해서실행하는문장

More information

컴파일러

컴파일러 YACC 응용예 Desktop Calculator 7/23 Lex 입력 수식문법을위한 lex 입력 : calc.l %{ #include calc.tab.h" %} %% [0-9]+ return(number) [ \t] \n return(0) \+ return('+') \* return('*'). { printf("'%c': illegal character\n",

More information

Microsoft PowerPoint - semantics

Microsoft PowerPoint - semantics 제 3 장시맨틱스 (Semantics) Reading Chap 13 숙대창병모 Sep. 2007 1 3.1 Operational Semantics 숙대창병모 Sep. 2007 2 시맨틱스의필요성 프로그램의미의정확한이해 소프트웨어의정확한명세 소프트웨어시스템에대한검증혹은추론 컴파일러혹은해석기작성의기초 숙대창병모 Sep. 2007 3 의미론의종류 Operational

More information

Data structure: Assignment 1 Seung-Hoon Na October 1, Assignment 1 Binary search 주어진 정렬된 입력 파일이 있다고 가정하자. 단, 파일내의 숫자는 공백으로 구 분, file내에 숫자들은

Data structure: Assignment 1 Seung-Hoon Na October 1, Assignment 1 Binary search 주어진 정렬된 입력 파일이 있다고 가정하자. 단, 파일내의 숫자는 공백으로 구 분, file내에 숫자들은 Data structure: Assignment 1 Seung-Hoon Na October 1, 018 1 1.1 Assignment 1 Binary search 주어진 정렬된 입력 파일이 있다고 가정하자. 단, 파일내의 숫자는 공백으로 구 분, file내에 숫자들은 multiline으로 구성될 수 있으며, 한 라인에는 임의의 갯수의 숫자가 순서대로 나열될

More information

Frama-C/JESSIS 사용법 소개

Frama-C/JESSIS 사용법 소개 Frama-C 프로그램검증시스템소개 박종현 @ POSTECH PL Frama-C? C 프로그램대상정적분석도구 플러그인구조 JESSIE Wp Aorai Frama-C 커널 2 ROSAEC 2011 동계워크샵 @ 통영 JESSIE? Frama-C 연역검증플러그인 프로그램분석 검증조건추출 증명 Hoare 논리에기초한프로그램검증도구 사용법 $ frama-c jessie

More information

Java ...

Java ... 컴퓨터언어 1 Java 제어문 조성일 조건문 : if, switch 어떠한조건을조사하여각기다른명령을실행 if 문, switch 문 if 문 if - else 문형식 if 문형식 if ( 조건식 ) { 명령문 1; 명령문 2;... if ( 조건식 ) { 명령문 1; 명령문 2;... else { 명령문 a; 명령문 b;... 예제 1 정수를입력받아짝수와홀수를판별하는프로그램을작성하시오.

More information

Semantic Consistency in Information Exchange

Semantic Consistency in Information Exchange 제 6 장제어 (Control) 6.1 구조적프로그래밍 (Structured Programming) 6.2 예외 (Exceptions) Reading Chap. 7 숙대창병모 1 6.1 구조적프로그래밍 숙대창병모 2 Fortran 제어구조 10 IF (X.GT. 0.000001) GO TO 20 11 X = -X IF (X.LT. 0.000001) GO TO

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 1,..... @ 1 Green Project 1991 Oak Java 1995. 5 December '90 by Patrick Naughton, Mike Sheridan and James Gosling Embedded in various consumer electronic device 1992. 9. 3 Star 7 1993 www portability

More information

BACK TO THE BASIC C++ 버그 헌팅: 버그를 예방하는 11가지 코딩 습관

BACK TO THE BASIC C++ 버그 헌팅: 버그를 예방하는 11가지 코딩 습관 Hanbit ebook Realtime 30 C++ 버그 헌팅 버그를 예방하는 11가지 코딩 습관 Safe C++ 블라디미르 쿠스퀴니르 지음 / 정원천 옮김 이 도서는 O REILLY의 Safe C++의 번역서입니다. BACK TO THE BASIC C++ 버그 헌팅 버그를 예방하는 11가지 코딩 습관 BACK TO THE BASIC C++ 버그 헌팅 버그를

More information

제 1 장 기본 개념

제 1 장 기본 개념 이진트리순회와트리반복자 트리순회 (tree traversal) 트리에있는모든노드를한번씩만방문 순회방법 : LVR, LRV, VLR, VRL, RVL, RLV L : 왼쪽이동, V : 노드방문, R : 오른쪽이동 왼쪽을오른쪽보다먼저방문 (LR) LVR : 중위 (inorder) 순회 VLR : 전위 (preorder) 순회 LRV : 후위 (postorder)

More information

PowerPoint Template

PowerPoint Template 16-1. 보조자료템플릿 (Template) 함수템플릿 클래스템플릿 Jong Hyuk Park 함수템플릿 Jong Hyuk Park 함수템플릿소개 함수템플릿 한번의함수정의로서로다른자료형에대해적용하는함수 예 int abs(int n) return n < 0? -n : n; double abs(double n) 함수 return n < 0? -n : n; //

More information

Microsoft PowerPoint - Chapter_04.pptx

Microsoft PowerPoint - Chapter_04.pptx 프로그래밍 1 1 Chapter 4. Constant and Basic Data Types April, 2016 Dept. of software Dankook University http://embedded.dankook.ac.kr/~baeksj 이장의강의목표 2 기본자료형문자표현방식과문자자료형상수자료형변환 기본자료형 (1/8) 3 변수 (Variables)

More information

C 프로그래밍 언어 입문 C 프로그래밍 언어 입문 김명호저 숭실대학교 출판국 머리말..... C, C++, Java, Fortran, Python, Ruby,.. C. C 1972. 40 C.. C. 1999 C99. C99. C. C. C., kmh ssu.ac.kr.. ,. 2013 12 Contents 1장 프로그래밍 시작 1.1 C 10 1.2 12

More information

C++ Programming

C++ Programming C++ Programming 연산자다중정의 Seo, Doo-okok clickseo@gmail.com http://www.clickseo.com 목 차 연산자다중정의 C++ 스타일의문자열 2 연산자다중정의 연산자다중정의 단항연산자다중정의 이항연산자다중정의 cin, cout 그리고 endl C++ 스타일의문자열 3 연산자다중정의 연산자다중정의 (Operator

More information

Lab 3. 실습문제 (Single linked list)_해답.hwp

Lab 3. 실습문제 (Single linked list)_해답.hwp Lab 3. Singly-linked list 의구현 실험실습일시 : 2009. 3. 30. 담당교수 : 정진우 담당조교 : 곽문상 보고서제출기한 : 2009. 4. 5. 학과 : 학번 : 성명 : 실습과제목적 : 이론시간에배운 Singly-linked list를실제로구현할수있다. 실습과제내용 : 주어진소스를이용해 Singly-linked list의각함수를구현한다.

More information

Microsoft PowerPoint - chap06-2pointer.ppt

Microsoft PowerPoint - chap06-2pointer.ppt 2010-1 학기프로그래밍입문 (1) chapter 06-2 참고자료 포인터 박종혁 Tel: 970-6702 Email: jhpark1@snut.ac.kr 한빛미디어 출처 : 뇌를자극하는 C프로그래밍, 한빛미디어 -1- 포인터의정의와사용 변수를선언하는것은메모리에기억공간을할당하는것이며할당된이후에는변수명으로그기억공간을사용한다. 할당된기억공간을사용하는방법에는변수명외에메모리의실제주소값을사용하는것이다.

More information

Microsoft PowerPoint - chap04-연산자.pptx

Microsoft PowerPoint - chap04-연산자.pptx int num; printf( Please enter an integer: "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); } 1 학습목표 수식의 개념과 연산자, 피연산자에 대해서 알아본다. C의 를 알아본다. 연산자의 우선 순위와 결합 방향에

More information

본문01

본문01 Ⅱ 논술 지도의 방법과 실제 2. 읽기에서 논술까지 의 개발 배경 읽기에서 논술까지 자료집 개발의 본래 목적은 초 중 고교 학교 평가에서 서술형 평가 비중이 2005 학년도 30%, 2006학년도 40%, 2007학년도 50%로 확대 되고, 2008학년도부터 대학 입시에서 논술 비중이 커지면서 논술 교육은 학교가 책임진다. 는 풍토 조성으로 공교육의 신뢰성과

More information

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2 제 8 장. 포인터 목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2 포인터의개요 포인터란? 주소를변수로다루기위한주소변수 메모리의기억공간을변수로써사용하는것 포인터변수란데이터변수가저장되는주소의값을 변수로취급하기위한변수 C 3 포인터의개요 포인터변수및초기화 * 변수데이터의데이터형과같은데이터형을포인터 변수의데이터형으로선언 일반변수와포인터변수를구별하기위해

More information

독립기념관 7월호 3p

독립기념관 7월호 3p www.i815.or.kr 04 06 08 10 12 14 16 18 19 20 21 22 23 24 26 28 30 32 34 36 38 40 42 43 44 45 46 47 50 www.i815.or.kr 2006. JULY www.i815.or.kr 2006. JULY www.i815.or.kr 2006. JULY www.i815.or.kr 2006.

More information

중간고사

중간고사 중간고사 예제 1 사용자로부터받은두개의숫자 x, y 중에서큰수를찾는알고리즘을의사코드로작성하시오. Step 1: Input x, y Step 2: if (x > y) then MAX

More information

Chap 6: Graphs

Chap 6: Graphs 그래프표현법 인접행렬 (Adjacency Matrix) 인접리스트 (Adjacency List) 인접다중리스트 (Adjacency Multilist) 6 장. 그래프 (Page ) 인접행렬 (Adjacency Matrix) n 개의 vertex 를갖는그래프 G 의인접행렬의구성 A[n][n] (u, v) E(G) 이면, A[u][v] = Otherwise, A[u][v]

More information

10주차.key

10주차.key 10, Process synchronization (concurrently) ( ) => critical section ( ) / =>, A, B / Race condition int counter; Process A { counter++; } Process B { counter ;.. } counter++ register1 = counter register1

More information

Page 2 of 5 아니다 means to not be, and is therefore the opposite of 이다. While English simply turns words like to be or to exist negative by adding not,

Page 2 of 5 아니다 means to not be, and is therefore the opposite of 이다. While English simply turns words like to be or to exist negative by adding not, Page 1 of 5 Learn Korean Ep. 4: To be and To exist Of course to be and to exist are different verbs, but they re often confused by beginning students when learning Korean. In English we sometimes use the

More information

Chapter 4. LISTS

Chapter 4. LISTS C 언어에서리스트구현 리스트의생성 struct node { int data; struct node *link; ; struct node *ptr = NULL; ptr = (struct node *) malloc(sizeof(struct node)); Self-referential structure NULL: defined in stdio.h(k&r C) or

More information