CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 7, 2007 박성우.

Slides:



Advertisements
Similar presentations
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Advertisements

Programming Languages Section 1 1 Programming Languages Section 1. SML Fundamentals Xiaojuan Cai Spring 2015.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Patterns in ML functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Introduction to ML – Part 1 Frances Spalding. Assignment 1 chive/fall05/cos441/assignments/a1.ht m
CSE 341, Winter Type Systems Terms to learn about types: –Type –Type system –Statically typed language –Dynamically typed language –Type error –Strongly.
CSE-321 Programming Languages Polymorphism POSTECH May 15, 2006 박성우.
Chapter 41 Defining Classes and Methods Chapter 4.
Introduction to ML – Part 1 Kenny Zhu. Assignment 2 chive/fall07/cos441/assignments/a2.ht m
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Introduction to ML You will be responsible for learning ML on your own. Today I will cover some basics Read Robert Harper’s notes on “an introduction to.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Functional Programming Element of Functional Programming.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
CS235 Languages and Automata Department of Computer Science Wellesley College Introduction to Standard ML Wednesday, September 23, 2009 Reading: Beginning.
VARIABLES AND TYPES CITS1001. Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Scope.
1 SML fn x => e e 1 e 2 0, 1, 2,..., +, -,... true, false, if e then e else e patterns datatypes exceptions structures functors fun f x = e variables.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
CSE-321 Programming Languages Introduction to Functional Programming (Part II) POSTECH March 13, 2006 박성우.
Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
Chapter 6 Programming Languages (1) Introduction to CS 1 st Semester, 2015 Sanghyun Park.
Functional Programming Language OCaml Tutorial 科大 - 耶鲁联合研究中心
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
12/9/20151 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
CMSC 330: Organization of Programming Languages
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Introduction to Functional Programming
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
Today’s Agenda ML Development Workflow –Emacs –Using use –The REPL More ML –Shadowing Variables –Debugging Tips –Boolean Operations –Comparison Operations.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 8, 2006 박성우.
Functional Programming Lecture 1 - Introduction Professor Muffy Calder.
CSE-321 Programming Languages Introduction to Functional Programming POSTECH 박성우.
Functional Programming
Programming Languages and Compilers (CS 421)
Principles of programming languages 12: Functional programming
ML: a quasi-functional language with strong typing
Introduction to Computer Science / Procedural – 67130
CSE 341: Programming Languages Section 1
CSE 341: Programming Langs
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Elements of Programming Languages
FP Foundations, Scheme In Text: Chapter 14.
Agenda SML Docs First-Class Functions Examples Standard Basis
Agenda SML Docs First-Class Functions Examples Standard Basis
CSE 341 Section 5 Winter 2018.
CSE341: Programming Languages Lecture 12 Equivalence
CSE-321 Programming Languages Introduction to Functional Programming
CSE 341 Section 3 Nick Mooney Spring 2017.
CSE-321 Programming Languages Introduction to Functional Programming
CSE-321 Programming Languages Introduction to Functional Programming
CSE341: Programming Languages Lecture 12 Equivalence
CSE341: Programming Languages Lecture 12 Equivalence
Presentation transcript:

CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 7, 2007 박성우

2 Programming Paradigms Structural programming –C, Pascal, … Object-oriented programming –C++, Java, … Logic programming –Prolog, … Functional programming –SML, Haskell, Objective Caml, Lisp, Scheme, …

3 Outline Expressions and values Variables Functions Types Recursion Datatypes Pattern matching Higher-order functions Exceptions Modules

4 C A program consists of commands. –command = “do something” Nothing wrong: if (x == 1) then x = x + 1; else x = x - 1; Nothing wrong either: if (x == 1) then x = x + 1;

5 SML A program consists of expressions. –expression = “obtain a value” Nothing wrong: if (x = 1) then x + 1 else x - 1 But this does not make sense: if (x = 1) then x + 1 –what is the value if x <> 1 ?

6 Evaluation Expression Value An expression “evaluates” to a value. We “evaluate” an expression to obtain a value.

7 Integer Evaluation … 1 * 1 1

8 Boolean Evaluation 1 = 1 true 1 <> 1 false … 1 <> 0 true

9 An Integer Expression if 1 = ~1 then 10 else ~10 ~10 if false then 10 else ~10

10 Values as Expressions 1 ???

11 Everything is an Expression! 1 ~1 1 = ~1 10 ~10 if 1 = ~1 then 10 else ~10

12 Actually Not Everything Ill-formed expressions – if 1 = ~1 then 10 (x) – if 1 = ~1 then 10 else ~10 (x) if 1 = ~1 then 10 else ~10

13 Outline Expressions and values V Variables Functions Types Recursion Datatypes Pattern matching Higher-order functions Exceptions Modules

14 Variable Declaration - val x = 1 + 1; val x = 2 : int A variable x is “bound” to value 2. From now on, any occurrence of x is replaced by 2. - val y = x + x; val y = 4 : int

15 Local Declaration let val x = 1 val y = x + x val z = y + y in z + z end 8

16 Nested Local Declaration let val x = 1 in x + x end let val y = in y + y end let val y = let val x = 1 in x + x end in y + y end

17 Why “Local”? let val y = let val x = 1 in x + x end in x + y end okay???

18 Variables are NOT variable. The contents of a variable never change. –immutability of variables Surprise? –That’s because you are thinking about variables in imperative programming. variables in SML <> variables in C

19 Then Why Variables? Any advantage in using variables at all? let val x = 1 val y = x + x val z = y + y in z + z end ((1 + 1) + (1 + 1)) + ((1 + 1) + (1 + 1)) VS. What if it takes 10 hours to evaluate 1 ?

20 Outline Expressions and values V Variables V Functions Types Recursion Datatypes Pattern matching Higher-order functions Exceptions Modules

21 When is the first time you learned the concept of function?

22 즐거운 낱말 공부 시간 함수 ( 函數 ): 두 변수 x, y 간에 어떤 관계가 있어 x 의 변화에 따라 y 가 일정한 법칙으로 변화할 때 y 를 x 의 함수라 함. (function) ( 동아 마스타 국어사전 )

23 즐거운 한자 공부 시간 函 1. 함 ( 함 ). 2. 편지 ( 함 ) 3. 갑옷 ( 함 ) 4. 넣을, 들일 ( 함 ) 예 : ( 書函 ) 서함 : 책을 넣는 상자

24 Function = 函數 = Box Number!

25 Using a Box Number

26 Using a Box Number - Generalized … …

27 Function in SML = Box Number (fn x => x + 1) n =

28 Function Application We “apply” (fn x => x + 1) to n. x is called a formal argument/parameter. n is called an actual argument/parameter. … (fn x => x + 1) n

29 Evaluating a Function Application … … (fn x => x + 1) n n + 1

30 Functions in SML Nameless function –fn x => x + 1; Storing a nameless function to a variable –val incr = fn x => x + 1; Function declaration –fun incr x = x + 1;

31 Function Applications (fn x => x + 1) incr 1

32 First-class Objects First-class objects = primitive objects –can be stored in a variable. –can be passed as an argument to a function. –can be returned as a return value of a function. Examples: –integers –booleans –characters –floating-point numbers –…

33 First-class Objects in C First-class objects –integers –characters –floating-point numbers –pointers –structures –… Functions? –Function pointers are first-class objects. –But functions are not. Why? You cannot create new functions on the fly!

34 Functions = First-class Objects in SML Functions: –can be passed as an argument to a function. –can be returned as a return value of a function.

35 Box Number as Output … … …… such that

36 Box Number as Output … … x +x+x

37 x y+xy+x y Box Number as Output

38 x y fn y => y+x y+xy+x Box Number as Output

39 x y fn y => y+x y+xy+x Box Number as Output

40 x y fn y => y+x fn x => (fn y => y+x) y+xy+x Box Number as Output

41 In SML Recall the following declarations are equivalent: –val incr = fn x => x + 1; –fun incr x = x + 1; Then: –val add = fn x => (fn y => y + x); –fun add x = fn y => y + x; –fun add x y = y + x; add takes only one argument, not two! In fact, every function in SML takes only one argument.

42 Adding Two Integers (fn x => (fn y => y + x)) add 1 2 (fn y => y + 1)

43 Box Number as Input true,false)(

44 Box Number as Input true,false)( fn f => (f true, f false) f f f

45 Outline Expressions and values V Variables V Functions V Types Recursion Datatypes Pattern matching Higher-order functions Exceptions Modules

46 Types A type specifies what kind of value a given expression evaluates to. –1 + 1 : int –true andalso false : bool –#”A” : char –”hello” : string –(1, true) : int * bool –(1, ~1, true) : int * int * bool –1.0 : real –() : unit

47 Type Preservation Expression : T Value : T An evaluation preserves the type of a given expression.

48 Example let val x = 1 val y = x + x val z = y + y in z + z end 8 : int : int

49 Function Types T -> T’ –type of functions: taking arguments of type T returning values of type T’ Example: –val incr = fn x => x + 1; val incr = fn : int -> int –fun incr x = x + 1; val incr = fn : int -> int Explicit type annotation –val incr = fn (x:int) => x + 1; val incr = fn (x:int) : int => x + 1; –fun incr (x:int) = x + 1; fun incr (x:int) : int = x + 1;

50 x fn y => y+x fn x => (fn y => y+x) Type of add

51 fn y => y+x fn x => (fn y => y+x) Type of add int

52 fn x => (fn y => y+x) Type of add int int -> int

53 int -> (int -> int) Type of add int int -> int

54 What is the Type? true,false)( fn f => (f true, f false) f f f

55 f : bool -> int ? true,false)( fn f => (f true, f false) f f f : (bool -> int) -> int * int

56 But why is it f : bool -> int ?

57 Why not f : bool -> char ? true,false)( fn f => (f true, f false) f f f : (bool -> char) -> char * char

58 Then why not f : bool -> string ? f : bool -> int * string ? f : bool -> unit ? f : bool -> (int -> int) ? f : bool -> ? …

59 So we need Polymorphism.

60 Polymorph in Warcraft 2 Cost: 2000 Gold Mana 200 Range: 10 Time to Upgrade: 200 Time Units. Perhaps the most fearsome of the Mage spells, Polymorph alters the physical form of its target. This metamorphosis changes man to beast, forever warping both mind and body. This sorcery wholly transforms the victim into a creature of the wolds, thus losing their reasoning - making commands for direction or battle impossible. This turns any living creature into the critter for that map type such as Pig for Wasteland, Seal for Snow, Sheep for Forest, Boar for Swamp. Although the unit hasn't been killed it has been in effect killed as it cannot be turned back into the previous unit or commanded in anyway. Polymorph is good for instantly taking out units, especially costly and dangerous units. The primary use for Polymorph is for hit and run attacks against enemy Mages, Death Knights, and Gryphons. Polymorph is really helpful on defense, especially on water maps. When the enemy lands you can quickly Polymorph the most dangerous enemy units right after they unload from the Transport. Make a Mage with at least 200 Mana Invisible, sneak up to an enemy Mage or Dragon and Polymorph it. If it is sea, do the pop out of the Transport Polymorph then run. Often you can cast Polymorph before the enemy even notices it, there is no warning to enemy players that their units have been Polymorphs. Against inattentive players you might be able to Polymorph quite a few units using hit and run attacks before they catch on.

61 Polymorph in Warcraft II Polymorph Cost: 2000 Gold Mana 200 Range: 10 Time to Upgrade: 200 Time Units. Permanent effect You may cast polymorph on your ally units!

62 Polymorph in Warcraft III Temporary effect –60 seconds

63 Polymorph in World of Warcraft

64 Announcement Assignment 1 is out. –Due at 1am, March 14 (next Wednesday) –If you don't find your handin directory, me. Course notes –Chapter 1 is almost finished. –Not finished: Section 10 (higher-order functions) Section 12 (modules)