Download presentation
Presentation is loading. Please wait.
Published byLionel Ferguson Modified over 9 years ago
1
CSED101 INTRODUCTION TO COMPUTING FUNCTION ( 함수 ) 유환조 Hwanjo Yu
2
Function ( 함수 ) When same expressions are computed multiple times, functions can be used. E.g., We want to compute x 4 for some integer x like 2*2*2*2 + 3*3*3*3 + 5*5*5*5. Assume there is a function f(x) that returns x 4 for an integer x. Then, we can express f(2) + f(3) + f(5), which is much convenient. –2–2
3
Function: basic Define a function fun x -> x * x The x in the left is called argument, and x * x is called the body of function. Can have multiple arguments like “fun x y -> x*y” fun x y z -> x*y+z fun x y z w -> x*y+z*w fun x y z w v -> (x*y+z*w)*v Fun … -> –3–3
4
Function: basic Arguments must have different names “fun x y x -> x + y” => error, which x? Can use local variables within a function “fun x y -> let x = x+y in x+x” => f(x, y) = 2(x+y) –4–4
5
Function: application Function do nothing until it is “called”. … (fun x -> x * x) 1 (fun x y -> x*y) (1+1) (2+2) (fun x y z -> x*y+z) 1 1 (1+1) Each expression is an argument of the function –5–5
6
Function: name A function without name cannot be called later because it doesn’t have a name to call. A function must have a name to be called later. Try in OCAML let f = fun x -> x*x;; f 1;; f 2;; Val f: int -> int = –6–6
7
Function: name scope Function within an expression let f = fun x -> x*x in (f 1) + (f 2);; f;; f cannot be used outside the expression since it is defined like a local variable. –7–7
8
Function: variable Variables used in a function body work as constants let x = 1;; let f = fun y -> x*y;; f 0;; let x = -1;; f 0;; –8–8
9
Function: variable Other case let f = fun a -> let g = fun x -> a*x in (g 1) + (g 2);; f 1;; f 2;; Whenever f is called, g is newly defined. –9–9
10
Function: definition let = fun.. -> ;; let.. = ;; Eg., let f x y z = x*y+z;; let g x y z w = x*y*+z*w;; let h x y z w v = (x*y+z*w)*v;; let f x = x + 1 in f 0;; let f a = let g x = a*x in (g 1) + (g 2);; –10
11
Function: precedence Function has the highest precedence f 0 + f 1 = (f 0) + (f 1) –11
12
Function: type Function arguments and output may have different types. let f x = x > 0;; val f: int -> bool = let f x y = x+1 < y-1;; val f: int -> int -> bool = let f x = x + x;; f 0.0;; –12
13
Function: type let f x y z = x > 0 && y > 0.0 && z;; val f: int -> float -> bool -> bool = f 1 1.0 true;; f 1.0 1 false;; –13
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.