CSED101 INTRODUCTION TO COMPUTING FUNCTION ( 함수 ) 유환조 Hwanjo Yu.
-
Upload
lionel-ferguson -
Category
Documents
-
view
233 -
download
0
description
Transcript of CSED101 INTRODUCTION TO COMPUTING FUNCTION ( 함수 ) 유환조 Hwanjo Yu.
CSED101 INTRODUCTION TO COMPUTINGFUNCTION ( 함수 )
유환조Hwanjo Yu
Function ( 함수 ) When same expressions are computed
multiple times, functions can be used. E.g., We want to compute x4 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
x4 for an integer x. Then, we can express f(2) + f(3) + f(5),
which is much convenient.
–2
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 <argument1> <argument2>… -> <body>
–3
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
Function: application Function do nothing until it is “called”. <Function> <Expression1>
<Expression2> … (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
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 = <fun>
–6
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
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
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
Function: definition let <name> = fun <arg1><arg2> .. ->
<body>;; let <name> <arg1> <arg2> .. = <body>;; 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
Function: precedence Function has the highest precedence f 0 + f 1 = (f 0) + (f 1)
–11
Function: type Function arguments and output may
have different types. let f x = x > 0;;
val f: int -> bool = <fun> let f x y = x+1 < y-1;;
val f: int -> int -> bool = <fun> let f x = x + x;; f 0.0;;
–12
Function: type let f x y z = x > 0 && y > 0.0 && z;;
val f: int -> float -> bool -> bool = <fun> f 1 1.0 true;; f 1.0 1 false;;
–13