CSCC24 Functional Programming Typing, Scope, Exceptions ML

Size: px
Start display at page:

Download "CSCC24 Functional Programming Typing, Scope, Exceptions ML"

Transcription

1 CSCC24 Functional Programming Typing, Scope, Exceptions ML Carolyn MacLeod 1 winter Based on slides by Anya Tafliovich, with many thanks to Gerald Penn and Sheila McIlraith.

2 motivation Consider the following Scheme function definition: (define foobar (lambda (x) (if (even? x) (first x) (rest x)))) Anything wrong?

3 motivation Consider the following Scheme function definition: (define foobar (lambda (x) (if (even? x) (first x) (rest x)))) Anything wrong? even? expects a number and first, rest expect a list = we ll get an error at run-time.

4 motivation Consider the following Scheme function definition: (define foobar (lambda (x) (if (even? x) (first x) (rest x)))) Anything wrong? even? expects a number and first, rest expect a list = we ll get an error at run-time. We are able to figure it out before run-time. Can t a PL support this kind of reasoning?

5 What is the property of Scheme that is related to this property

6 3 What is the property of Scheme that is related to this property Dynamic typing

7 3 What is the property of Scheme that is related to this property Dynamic typing What other language do you know with dynamic typing?

8 3 What is the property of Scheme that is related to this property Dynamic typing What other language do you know with dynamic typing? Python

9 It could be worse! motivation

10 It could be worse! motivation At least Scheme checks that x is a list (cons pair) before accessing memory in the execution of (rest x).

11 It could be worse! motivation At least Scheme checks that x is a list (cons pair) before accessing memory in the execution of (rest x). In fact, Scheme is type safe: it will never execute if op is not applicable to arg. (op arg)

12 It could be worse! motivation At least Scheme checks that x is a list (cons pair) before accessing memory in the execution of (rest x). In fact, Scheme is type safe: it will never execute if op is not applicable to arg. (op arg) What s a language you know that is not type safe?

13 It could be worse! motivation At least Scheme checks that x is a list (cons pair) before accessing memory in the execution of (rest x). In fact, Scheme is type safe: it will never execute if op is not applicable to arg. (op arg) What s a language you know that is not type safe? C is one you most likely know.

14 It could be worse! motivation At least Scheme checks that x is a list (cons pair) before accessing memory in the execution of (rest x). In fact, Scheme is type safe: it will never execute if op is not applicable to arg. (op arg) What s a language you know that is not type safe? C is one you most likely know. Languages which are not type safe (e.g., C) allow unsafe memory accesses: a major source of security vulnerabilities.

15 5 motivation Want to catch all errors at compile-time.

16 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible.

17 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them.

18 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them. Catch as many errors as possible?

19 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them. Catch as many errors as possible? Costly: programmers expertise, computational resources, etc.

20 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them. Catch as many errors as possible? Costly: programmers expertise, computational resources, etc. Slower development, less expressive languages.

21 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them. Catch as many errors as possible? Costly: programmers expertise, computational resources, etc. Slower development, less expressive languages. Used in development of safety-critical systems.

22 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them. Catch as many errors as possible? Costly: programmers expertise, computational resources, etc. Slower development, less expressive languages. Used in development of safety-critical systems. Compromise: type systems.

23 5 motivation Want to catch all errors at compile-time. Extremely difficult, if not impossible. Identify a certain class of errors and guarantee to catch all of them. Catch as many errors as possible? Costly: programmers expertise, computational resources, etc. Slower development, less expressive languages. Used in development of safety-critical systems. Compromise: type systems. Guarantees range widely: from basic safety of memory accesses to just about anything you want.

24 A type is: typing A name for a set of values and some operations which can be performed on that set of values. A collection of computational entities that share some common property.

25 7 typing Some examples of types (in ML notation): int : the integers (and their operations). real : the real numbers (and their operations). string : the strings (and their operations). bool : the booleans (and their operations). int bool : the functions that take integers as input and return booleans as output.

26 typing Some examples of types (in ML notation): int : the integers (and their operations). real : the real numbers (and their operations). string : the strings (and their operations). bool : the booleans (and their operations). int bool : the functions that take integers as input and return booleans as output. What constitutes a type is language dependent.

27 Benefits of having a type system: typing Easier to debug programs: compiler can catch many errors. Static analysis: a lot of useful information about the program can be obtained at compile-time. Efficiency: typing can be used by the compiler to generate quicker code. Correctness: typing can be used (by the programmer or by the compiler) to prove correctness of code. Documentation: types declare your intent with well-chosen names.

28 Recall - last lecture We saw this Scheme function definition: (define foobar (lambda (x) (if (even? x) (first x) (rest x)))) What is wrong with the code?

29 Recall - last lecture We saw this Scheme function definition: (define foobar (lambda (x) (if (even? x) (first x) (rest x)))) What is wrong with the code? What programming language feature would stop us creating programs with this kind of bugs?

30 10 typing A programming language is type safe if no program is allowed to violate its type distinctions. The process of verifying and enforcing the constraints of types is called type checking. Type checking can either occur at compile-time (static type checking) or at run-time (dynamic type checking).

31 11 Dynamic type checking: static vs dynamic typing Static type checking:

32 static vs dynamic typing Dynamic type checking: Performed at run-time. Slower execution: need to carry type information around, lots of run-time checks. More flexible. Easier refactoring. Static type checking: Faster execution. Compiler can do a lot of optimization. Some argue that resulting programs are safer. Some argue that resulting programs are more elegant and modular. Some argue that programmers will write horrible code to get around a static type-checker. 11

33 12 static typing Explicit static typing: code contains type annotations. For example, in Java: Variable declarations int x,y,z; Function headers public static void main(string[] arg)

34 static typing Explicit static typing: code contains type annotations. For example, in Java: Variable declarations int x,y,z; Function headers public static void main(string[] arg) Type inference: infer all types from the code that does not contain explicit type annotations. fun foo(x,y,z) = if x then y + z else 0.0;

35 static typing Explicit static typing: code contains type annotations. For example, in Java: Variable declarations int x,y,z; Function headers public static void main(string[] arg) Type inference: infer all types from the code that does not contain explicit type annotations. fun foo(x,y,z) = if x then y + z else 0.0; x must be boolean

36 static typing Explicit static typing: code contains type annotations. For example, in Java: Variable declarations int x,y,z; Function headers public static void main(string[] arg) Type inference: infer all types from the code that does not contain explicit type annotations. fun foo(x,y,z) = if x then y + z else 0.0; x y, z must be boolean must be reals

37 static typing Explicit static typing: code contains type annotations. For example, in Java: Variable declarations int x,y,z; Function headers public static void main(string[] arg) Type inference: infer all types from the code that does not contain explicit type annotations. fun foo(x,y,z) = if x then y + z else 0.0; x y, z must be boolean must be reals the return value is real

38 static typing Explicit static typing: code contains type annotations. For example, in Java: Variable declarations int x,y,z; Function headers public static void main(string[] arg) Type inference: infer all types from the code that does not contain explicit type annotations. fun foo(x,y,z) = if x then y + z else 0.0; x y, z must be boolean must be reals the return value is real foo : bool * real * real -> real

39 Features of Standard ML What is ML? ML is an ALGOL family language, a child of Pascal and Lisp, and a distant cousin of C ML was designed as the Meta- Language of the Logic for Computable Functions (LCF) System. Its original purpose was for writing programs that would attempt to construct mathematical proofs. Question - What have we seen that is similar? ML is a functional language, although ML can be written in a more imperative style. Arguably, you can call it a mostly functional language, or a function-oriented imperative language.

40 14 Features of Standard ML Modular:Supports modules and interfaces, determining what components and types from the module are visible outside. Strict Pass By Value: The arguments of the function are evaluated before the beginning of the function being evaluated. Polymorphic: Supports both data type and function polymorphism. Type System: The ML type system is considered one of the cleanest in any language Static typing Type inference Type safe Functions are first class values: Functions can be defined, passed as arguments, and returned as function results. Garbage Collection Exception Handling

41 A few examples Standard ML

42 ML Examples (* This is a comment in SML *) fun factorial (n:int):int = if n = 0 then 1 else n * factorial(n-1) Notice, we use = both for comparison, and for the function definition. We use an infix notation, unlike in Scheme. In this example, we have explicit static typing.

43 ML Examples Another form of writing function definitions: (* Our first fibonacci solution in Scheme, translated to ML *) fun fib 1 = 1 fib 2 = 1 fib (n) = fib(n-1) + fib(n-2) This is also an example of type inference - notice that this version does not specify types for the input and output of fib, however, when compiled or entered into the interpreter, it gives a type signature of val fib = fn : int -> int

44 18 type inference Trade-off: Want the language to be expressive. Want tractable type inference. ML is designed to make type inference tractable. Widely regarded as an important language innovation.

45 19 ML data types Basic types: unit : the only member is (). bool : booleans. int : integers. real : reals. string : strings.

46 19 ML data types Basic types: unit : the only member is (). bool : booleans. int : integers. real : reals. string : strings. More types: ( type 0 type 1... type n ) : tuples. type list : lists. input-type output-type : functions.

47 20 ML basic types unit: this type has only one element () - (); val it = () : unit ML assigns the last evaluated value to the special variable it. Reading the above snippet of the ML interpreter session: evaluate (), please the special variable it now has the value () of type unit

48 ML basic types bool: this type has two elements: true and false. Operations on bools: not, tostring,... Special operators: andalso, orelse. For example: - if (not true andalso false) orelse true then true else false; val it true : bool

49 ML basic types The structure of lists in ML is the same as in Scheme and Prolog. Strings must have elements of all the same type. - hd [1,2,3]; val it = 1 : int - tl [1,2,3]; val it = [2,3] : int list - "a" :: ["b","c"]; val it = ["a","b","c"] : string list - [1,2]@[3]; val it = [1,2,3] : int list These are the equivalents of first/car, rest/cdr, and cons in Scheme. operator is used like append in Scheme.

50 ML basic types fun elem_to_list [] = [] elem_to_list (h::t) = [h] :: (elem_to_list t)

51 24 int: {... 2, 1, 0, 1, 2,... } ML basic types Operations: +,,,, div, mod, <, >, =, <=, >=, <> For example: * 2-3 div 2; val it = 16 : int - 5 mod 2 >= 6 mod 2; val it = true : bool

52 ML basic types int: {... 2, 1, 0, 1, 2,... } Note the use of ~ for negation. Here s why: - is a binary operator while ~ is a unary operator. - -5; stdin:27.1 Error: expression or pattern begins with infix identifier "-" stdin: Error: operator and operand don t agree [literal] operator domain: Z * Z operand: int in expression: ~5; val it = ~5 : int

53 real: { 1.0, , 11.7,... } ML basic types Operations: +,,, <, >, <=, >= Note: You cannot mix reals and integers in one expression. Every ML expression has a type. If an expression cannot be typed, we get an error.

54 For example: ML basic types ; stdin: Error: operator and operand don t agree operator domain: int * int operand: int * real in expression: Understanding the error message... Why int? For mathematical operators, if the type is not specified (or inferred), then type int is assumed.

55 More examples: ML basic types - 2; val it = 2 : int - 2.0; val it = 2.0 : real - real(2); val it = 2.0 : real ; val it = 0.5 : real - real(2) - 1.5; val it = 0.5 : real

56 ML basic types Note that SML inspects the leftmost argument first. For example: ; stdin: Error: operator and operand don t agree operator domain: real * real operand: real * int in expression: Now it expects two reals.

57 30 ML basic types Note that while <, <=, >, >= are defined for all numeric types, = and <> are, for example, not defined for reals. In fact, = : a * a -> bool <> : a * a -> bool In ML a means the type for which equality is defined. With reals we can use a <= b andalso b >= a. Or, much better, use real arithmetic: - Real.==(1.0, 1.0); val it = true : bool - Real.==(1.0, ); val it = true : bool

58 31 ML basic types string: { Hello, world, CSCC24 is fun!,... } Operations: ^ for concatenation For example: - "Hello"; val it = "Hello" : string - "Hello" ^ " " ^ "Jim"; val it = "Hello Jim" : string

59 32 ML data types Basic types: unit : the only member is (). bool : booleans. int : integers. real : reals. string : strings.

60 32 ML data types Basic types: unit : the only member is (). bool : booleans. int : integers. real : reals. string : strings. More types: ( type 0 type 1... type n ) : tuples. type list : lists. input-type output-type : functions.

61 ML types A tuple packs together several types. - ("foo", "bar"); val it = ("foo","bar") : string * string - ("foo", "bar", 123); val it = ("foo","bar",123) : string * string * int - ("foo", (123, 456)); val it = ("foo",(123,456)) : string * (int * int) Operations: accessing component N of a tuple t is written #N t. - #2 ("foo", 123, 3.14); val it = 123 : int

62 ML types In ML all elements in a list must have the same type. - [1,2,3,4]; val it = [1,2,3,4] : int list - ["cscc24","is","fun"]; val it = ["cscc24","is","fun"] : string list - [("foo",1.0),("bar",3.14)]; val it = [("foo",1.0),("bar",3.14)] : (string * real) list [ ] (or nil) is the empty list. Constructor: :: Selectors: hd, tl More null, length, map, foldr,... 34

63 Some examples: ML types - "foo"::["bar","foobar"]; val it = ["foo","bar","foobar"] : string list - [1,2]@[3,4]; val it = [1,2,3,4] : int list - hd [1,2]; val it = 1 : int - tl [1,2]; val it = [2] : int list

64 36 ML syntax A variable declaration in ML looks like: val name = expr

65 36 ML syntax A variable declaration in ML looks like: val name = expr val x =

66 36 ML syntax A variable declaration in ML looks like: val name = expr val x = (define x ( ))

67 37 ML functions The syntax for anonymous functions in ML is: fn arg => body

68 37 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1

69 37 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1))

70 37 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1))

71 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body

72 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1

73 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1)))

74 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1)))

75 37 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1))) Or: fun name arg = body

76 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1))) Or: fun name arg = body fun inc x = x + 1

77 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1))) Or: fun name arg = body fun inc x = x + 1 (define (inc x) (+ x 1))

78 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1))) Or: fun name arg = body fun inc x = x + 1 (define (inc x) (+ x 1))

79 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1))) Or: fun name arg = body fun inc x = x + 1 (define (inc x) (+ x 1)) In ML every function accepts exactly one argument.

80 ML functions The syntax for anonymous functions in ML is: fn arg => body fn x => x + 1 (lambda (x) (+ x 1)) Giving a name to a function: Or: val name = fn arg => body val inc = fn x => x + 1 (define inc (lambda (x) (+ x 1))) fun name arg = body fun inc x = x + 1 (define (inc x) (+ x 1)) In ML every function accepts exactly one argument.this argument could be a tuple.

81 38 ML types The type of a function is determined by the type of the input and the type of the output. Some examples: - fun inc x = x + 1; val inc = fn : int -> int - fun addinc(x,y) = x + y + 1; val addinc = fn : int * int -> int - fun optinc(x,y,c) = if c then x + y + 1 else x + y; val optinc = fn : int * int * bool -> int

82 39 parametric polymorphism What is the type of fn x => x?

83 parametric polymorphism What is the type of fn x => x? - fun id x = x; val id = fn : a -> a - id 324; val it = 324 : int - id 3.14; val it = 3.14 : real - id "foo"; val it = "foo" : string - id [1,2,3]; val it = [1,2,3] : int list - id (fn x => x + 1); val it = fn : int -> int

84 - fun id x = x; val id = fn : a -> a parametric polymorphism The a in ML stands for α. It is a type variable.

85 - fun id x = x; val id = fn : a -> a parametric polymorphism The a in ML stands for α. It is a type variable. id is a polymorphic function.

86 - fun id x = x; val id = fn : a -> a parametric polymorphism The a in ML stands for α. It is a type variable. id is a polymorphic function. α α means for every valid type α, α α α α α

87 - fun id x = x; val id = fn : a -> a parametric polymorphism The a in ML stands for α. It is a type variable. id is a polymorphic function. α α means for every valid type α, α α α α α When id is applied to 324, the type variable α is instantiated to int.

88 Examples: parametric polymorphism fun choose (a,b,c) = if a then b else c;

89 Examples: parametric polymorphism fun choose (a,b,c) = if a then b else c; choose : bool * a * a -> a;

90 Examples: parametric polymorphism fun choose (a,b,c) = if a then b else c; choose : bool * a * a -> a; fun swap (x,y) = (y,x);

91 Examples: parametric polymorphism fun choose (a,b,c) = if a then b else c; choose : bool * a * a -> a; fun swap (x,y) = (y,x); swap : a * b -> b * a;

92 parametric polymorphism What is the type of the following function? fun length lst = if (null lst) then 0 else 1 + length (tl lst);

93 parametric polymorphism What is the type of the following function? fun length lst = if (null lst) then 0 else 1 + length (tl lst); length : a list -> int

94 parametric polymorphism What is the type of the following function? fun length lst = if (null lst) then 0 else 1 + length (tl lst); length : a list -> int List is a polymorphic data type.

95 With named functions: currying - fun sum x y = x + y; val sum = fn : int -> int -> int - sum 2; val it = fn : int -> int - sum 2 3; val it = 5 : int

96 With anonymous functions: currying - fn x => fn y => x + y; val it = fn : int -> int -> int - (fn x => fn y => x + y) 2; val it = fn : int -> int - (fn x => fn y => x + y) 2 3; val it = 5 : int

97 pattern matching Value declaration (general form): val <pat> = <exp> - val mytuple = ("foo", "bar"); val mytuple = ("foo","bar") : string * string - val (x,y) = mytuple; val x = "foo" : string val y = "bar" : string - val mylist = [1,2,3,4]; val mylist = [1,2,3,4] : int list - val h::r = mylist; stdin: Warning: binding not exhaustive h :: r =... val h = 1 : int val r = [2,3,4] : int list 45

98 pattern matching is don t care : matches everything, binds nothing - val mytuple = ( foo, bar ); val mytuple = ("foo","bar") : string * string - val (first, _) = mytuple; val first = "foo" : string - val h::_ = [1,2,3]; stdin: Warning: binding not exhaustive h :: _ =... val h = 1 : int

99 pattern matching Function declaration with pattern matching: fun <name> <pattern1> = <exp1> <name> <pattern2> = <exp2>.. <name> <patternn> = <expn>; This means: the function name is name. It takes one argument (as any other ML function). It tries to match the argument to pattern1. If it succeeds, it returns value of exp1. Otherwise, tries to match the argument to pattern2. Etc, etc.

100 pattern matching For example we can (and should!) rewrite len to use pattern matching: fun len [] = 0 len (x::xs) = 1 + len xs; len : a list -> int Non-exhaustive patterns: - fun len (x::xs) = 1 + len xs; stdin... Warning: match nonexhaustive x :: xs =>... val len = fn : a list -> int - len [1,2,3]; uncaught exception nonexhaustive match failure raised at:...

101 pattern matching Function firstlist takes a list of pairs and returns the list consisting of the first elements only. For example: firstlist [] ==> [] firstlist [(1,2),(1,3)] ==> [1,1] firstlist [(1,"a"),(2,"b"),(3,"c")] ==> [1,2,3] firstlist [([],"a"),([1],"b"),([1,2],"c")] ==> [[],[1],[1,2]] fun firstlist [] = [] firstlist ((e1,e2)::es) = e1::(firstlist es); firstlist : ( a * b) list -> a list

102 Syntax of an ML let expression: let <declaration> <declaration>... in <expression> end ML notes

103 Example: ML notes fun reverse lst = let fun reverseacc [] acc = acc reverseacc (x::xs) acc = reverseacc xs (x::acc) in reverseacc lst [] end; reverse : a list -> a list - reverse [1,2,3]; val it = [3,2,1] : int list

104 52 ML notes Function application is left-associative: Example: - reverse 1::[2,3]; f g h == (f g) h... Error: operator and operand don t agree operator domain: Z list operand: int in expression: reverse 1 - reverse (1::[2,3]); val it = [3,2,1] : int list

105 -val i = 3 : count; val i = 3: count type synonyms We can give existing types new names. Syntax: type new type = ty new type becomes an alias (a synonym) for the existing type ty. -type float = real; type float = real -type count = int and average = real; type count = int type average = real -val f : float = 2.3; val f = 2.3: float

106 54 type synonyms But notice float, real, and average are all of the same base type, i.e. real -val f : float = 2.3; val f = 2.3 : float -val a = f : average; val a = 2.3 : average -val sum = a+f; val sum = 4.6 : average -val sum = f+a; val sum = 4.6 : float

107 55 user defined datatypes General Syntax: datatype new_type = Cons1 of type1 Cons2 of type2... ConsN of typen Defines a new type called new type. type1,...,typen are previously defined types. Cons1,...,ConsN are constructors. They are used to create a value of new type type. of type is omitted if a constructor does not need any argument (such constructors are called constants).

108 56 enumerated types All constructors are constants (no argument). Example: -datatype color = Red Blue Green; datatype color = Blue Green Red -val c = Red; val c = Red : color -fun colorstr Red = "Red" colorstr Blue = "Blue" colorstr Green= "Green"; val colorstr = fn : color -> string -colorstr c; val it = "Red" : string

109 57 Create union of different types: variant types datatype number = R of real I of int; val n1 = I 2; val n2 = R 3.0; val lst = [R 2.2, I 3, I 4, R 0.1]; (* val lst = [R 2.2,I 3,I 4,R 0.1] : number list *)

110 variant types datatype number = R of real I of int; val lst = [R 2.2, I 3, I 4, R 0.1]; fun sumints [] = 0 sumints ((I x)::rest) = x + sumints rest sumints ((R x)::rest) = sumints rest; sumints : number list -> int; sumints lst; (* val it = 7 : int *)

111 recursive types A datatype can be recursive: e.g. a linked list datatype llist = Nil Node of int * llist; (* datatype llist = Nil Node of int * llist *) val x = Nil; (* val x = Nil : llist *) val y = Node (5,Nil); (* val y = Node (5,Nil) : llist *) val z = Node(3, Node(2, Node(1,Nil))); (* val z = Node (3,Node (2,Node #)) : llist *)

112 recursive types datatype llist = Nil Node of int * llist; (* datatype llist = Nil Node of int * llist *) (* length of a linked list *) fun len Nil = 0 len (Node (_,xs)) = 1 + len xs; len : llist -> int len z; (* val it = 3 : int*)

113 recursive types What about a polymorphic linked list? datatype a llist = Nil Node of a * ( a llist); (* datatype a llist = Nil Node of a * a llist *) val y = Node (5,Nil); (* val y = Node (5,Nil) : int llist *) val z = Node("A", Node("B",Nil)); (* val z = Node ("A",Node ("B",Nil)) : string llist *)

114 recursive types datatype a llist = Nil Node of a * ( a llist); (* datatype a llist = Nil Node of a * a llist *) fun len Nil = 0 len (Node (_,xs)) = 1 + len xs; len : a llist -> int len y; (* val it = 1 : int *) len z; (* val it = 2 : int *)

115 recursive types Example: Tree representation of simple mathematical expressions. ( 3 + 2) + (( 1) + 4) 7) add add mult abs 2 add 7 neg neg 4 3 What is the datatype we need? 1 63

116 The datatype: recursive types datatype math_tree = Leaf of int Unary of (int -> int) * math_tree Binary of (int * int -> int) * math_tree * math_tree

117 The tree in the figure: recursive types val t = Binary(op +, Binary(op +, Unary((fn x => if x > 0 then x else ~x), Unary (op ~, Leaf 3)), Leaf 2), Binary(op *, Binary(op +, Unary(op ~, Leaf 1), Leaf 4), Leaf 7))

118 Evaluating the tree: recursive types (* evaluate the math_tree *) fun eval (Leaf n) = n eval (Unary (f,t)) = f (eval t) eval (Binary (f,l,r)) = f (eval l,eval r); eval : math_tree -> int - eval t; val it = 26 : int

119 SML notes mutual recursion Let s mimic the Scheme definitions of even and odd: fun even 0 = true even x = odd (x - 1); fun odd 0 = false odd x = even (x - 1); Error: unbound variable or constructor: odd

120 68 Use the keyword and. fun even 0 = true even x = odd (x - 1) and odd 0 = false odd x = even (x - 1); even : int -> bool; odd : int -> bool mutual recursion even 42; (* val it = true : bool *) odd 42; (* val it = false : bool *)

121 69 mutually recursive types Example: a tree with labeled branches: datatype a tree = Empty Node of a branch * a branch and a branch = Branch of a * a tree;

122 The tree in the figure: mutually recursive types val lt = Node(Branch(1, Node(Branch(2, Empty), Branch(3, Node(Branch(4, Empty), Branch(5, Empty))))), Branch(6, Node(Branch(7, Empty), Branch(8, Empty))));

123 mutually recursive types datatype a tree = Empty Node of a branch * a branch and a branch = Branch of a * a tree Return the list of branch labels, in order: fun listtree Empty = [] listtree (Node (l,r)) = (listbranch (listbranch r) and listbranch (Branch (b,t)) = b :: (listtree t); listtree : a tree -> a list; listbranch : a branch -> a list listtree t; (* val it = [1,2,3,4,5,6,7,8] : int list *)

124 72 recursive types 1. A powerful tool for constructing new types. 2. The structure of the datatype suggests the structure of the recursive function on the datatype.

125 recursive types Recall our CFG for arithmetic expressions: <expn> --> <expn> + <expn> <expn> - <expn> <expn> * <expn> <expn> / <expn> <identifier> <literal> Let s define a (somewhat) corresponding datatype: datatype expn = Plus of expn * expn Minus of expn * expn Times of expn * expn Divn of expn * expn Num of real;

126 recursive types datatype expn = Plus of expn * expn Minus of expn * expn Times of expn * expn Divn of expn * expn Num of real; For example: 5 + 7*(-2) - 8 / 4 val e = Minus(Plus(Num 5.0, Times(Num 7.0, Num ~2.0)), Divn(Num 8.0, Num 4.0));

127 Evaluating the expression: recursive types fun eval (Num n) = n eval (Divn (x,y)) = (eval x) / (eval y) eval (Times (x,y)) = (eval x) * (eval y) eval (Minus (x,y)) = (eval x) - (eval y) eval (Plus (x,y)) = (eval x) + (eval y); eval : expn -> real; eval e; (* val it = ~11.0 : real *)

128 76 SML types, types, types... built-in types type synonyms, user-defined types enumerated, variant, union, recursive, mutually recursive recursion, higher-order functions (maps, folds)

129 using let in ML fun sumcube n = let fun cube x = x * x * x in if n = 0 then 0 else cube (n) + sumcube (n-1) end; Is it a good idea? cube is redefined every recursive call.

130 Better idea: using let in ML fun sumcube n = let fun cube x = x * x * x; fun sumc 0 = 0 sumc m = cube m + sumc (m-1) in sumc n end;

131 79 scope Name resolution: Given the use of a name (variable or function name), which instance of the entity with that name is referred to? Each use of a name must be associated with a single entity at run-time (i.e., an offset within a stack frame). The scope of a declaration of a name is the part of the program in which a use of that name refers to that declaration. The design of a language includes scope rules for resolving the mapping from the use of each name to its appropriate declaration.

132 80 A name is: scope visible to a piece of code if its scope includes that piece of code. local to a piece of code (block/ procedure/main program) if its declaration is within that piece of code. non-local to a piece of code if it is visible, but its declaration is not within that piece of code. A declaration of a name is hidden if another declaration supersedes it in scope.

133 scope example program L; var n: char; {n declared in L} procedure W; begin write(n); {n referenced in W} end; procedure D; var n: char; {n declared in D} begin n:= D ; {n referenced in D} W end; begin n:= L ; {n referenced in L} W; D

134 82 lexical scope Names are associated with declarations at compile time. Find the smallest block syntactically enclosing the reference and containing a declaration of the name. Example: The reference to n in W is associated with the declaration of n in L. The output is? Also called static scope.

135 83 dynamic scope Names are associated with declarations at run time. Find the most recent, currently active run-time stack frame containing a declaration of the name. Example: The reference to n in W is associated with two different declarations at two different times. The output is?

136 scope Lexical scope is based on the principle that consistent renaming of variables should not effect the value of an expression. Lexical scope goes a long way to establishing referential transparency easy to determine where variables obtain their values, because program itself (unlike run-time contexts) is not changing. Most modern languages (including Scheme and ML) use lexical scope, although early interpreted languages (LISP) used dynamic scope because of the flexibility and ease of implementation.

137 exceptions 85

138 85 exceptions Many functions are partial, i.e. they are only defined for a subset of the function s domain type. Other values in the domain type may be treated as exceptions: e.g., f (x) = 1/x Exceptions are a control construct. They provide a structured form of jump to exit a construct such as a function invocation or a block.

139 85 exceptions Many functions are partial, i.e. they are only defined for a subset of the function s domain type. Other values in the domain type may be treated as exceptions: e.g., f (x) = 1/x Exceptions are a control construct. They provide a structured form of jump to exit a construct such as a function invocation or a block. Terminate part of computation: Jump out of construct. Pass data as part of jump. Return to most recent site set up to handle exception. Unnecessary activation records may be deallocated (may need to free heap space, other resources).

140 86 Consider the following functions: fun f x = 1.0 / x; fun g x = hd x; fun h x = tl x; exceptions Will the type-checker complain? Is there a problem?

141 87 SML exceptions ML s exceptions (similar to the ones in Java or Python) provide a uniform way to handle errors, and eliminate the need for ad hoc, special exceptional return values from functions. When encountering a special case, raise an exception. The caller will catch/handle the exception and will take care of it. Primitive exceptions: 3 div 0 (* raises Div *) hd nil (* raises Empty *)

142 SML user-defined exceptions Defining an exception: exception <name> of <type> Raising an exception: raise <name> <arg> exception factneg; fun robustfact n= let fun fact 0 = 1 fact n = n * fact (n-1); in if n < 0 then raise factneg else fact n end; robustfact 5; (* val it = 120 : int *) robustfact ~5; (* uncaught exception factneg *)

143 SML exceptions Exceptions can have arguments, just like datatypes: exception factneg of int; fun robustfact n= let fun fact 0 = 1 fact n = n * fact (n-1); in if n < 0 then raise factneg n else fact n end;

144 Handling exceptions: SML exceptions <expr> handle <match1> => <expr1> <match2> => <expr2>... <matchn> => <exprn> Any restrictions on types?

145 Example: SML exceptions fun printfact n = print (Int.toString(robustFact n)^"\n") handle factneg x => print ("printfact "^(Int.toString x)^ ": argument must be >= 0\n"); (* val printfact = fn : int -> unit *) printfact ~5; (* printfact ~5: argument must be >= 0 val it = () : unit *)

146 SML exceptions Exceptions are handled according to dynamic scoping. exception e1 and e2 and e3; fun h 1 = raise e1 h 2 = raise e2 h 3 = raise e3 h _ = "ok"; fun g(n) = h(n) handle e2 => "error g2" e3 => "error g3"; fun f(n) = g(n) handle e1 => "error f1" e2 => "error f2"; f(4); f(3); f(2); f(1); f(0);

147 93 General dynamic scoping rule: exception handling Jump to most recently established handler on run-time stack. Dynamic scoping is not an accident: User knows how to handler error. Author of library function does not.

148 exceptions Why do we need exceptions in a strongly typed language?

149 exceptions Why do we need exceptions in a strongly typed language? Type-checker only checks types of parameters, not their values. In languages w/o exception handling, when an exception occurs, control goes to the OS and the program is terminated, or special code must be written to handle exceptions (e.g., pass special parameter or use return value of procedure to indicate status of program, etc.) In contrast, with exception handling, programs can fix the problem and continue, if desirable. Some uses: (see examples in Mitchell 8.2) Error handling (when no reasonable value can be returned). Efficiency (we don t like this one). Two types of exceptions in SML: Built-in exceptions. User-defined exceptions.

150 immutable data Variables (and data structures), once created and initialized, are immutable: they are never changed, updated, or stored into. Powerful guarantees of noninterference. Build new data structures (and let the old ones be garbage collected) instead of modifying old ones.

151 96 references functional programming no side effects ML separates pure expressions and side effects. Assignment is restricted to reference cells, which are of a different type. Assignment restrictions are enforced by the type system.

152 references Syntax: ref v creates a reference cell with value v!r returns contents of reference cell r r:=v sets contents of reference cell r to value v val x = ref 0; (* val x = ref 0 : int ref *) x; (* val it = ref 0 : int ref *)!x; (* val it = 0 : int *) x:=3; (* val it = () : unit *) x; (* val it = ref 3 : int ref *)!x; (* val it = 3 : int *) 97

153 references The type of a reference cell that contains value v of type α is α ref. Assignment to a reference cell must be consistent with the type of the reference cell Example: val x = ref "cscc24"; (* val x = ref "cscc24" : string ref *) x:=0; (* Error: operator and operand don t agree operator domain: string ref * string operand: string ref * int in expression: x := 0 *)

154 references (* abslst = fn : int ref list -> unit *) fun abslst [] = () abslst (x::rest) = (x:=abs(!x); abslst rest); val L = [ref ~1, ref 0, ref ~2]; (* val L = [ref ~1,ref 0,ref ~2] : int ref list*) abslst L; (* val it = () : unit *) L; (* val it = [ref 1,ref 0,ref 2] : int ref list *)

155 references (* abslst = fn : int list -> int list *) fun abslst [] = [] abslst (x::rest) = (abs x)::(abslst rest); fun abslst lst = map abs lst; val L = [~1, 0, ~2]; (* val L = [~1,0,~2] : int list *) abslst L; (* val it = [1,0,2] : int list *) L; (* val it = [~1,0,~2] : int list *)

156 101 ML functional type safe static type checking type inference polymorphic abstract data types exception handling static scope formal definition garbage collection immutable data types updatable references

CSC324 Functional Programming Typing, Exceptions in ML

CSC324 Functional Programming Typing, Exceptions in ML CSC324 Functional Programming Typing, Exceptions in ML Afsaneh Fazly 1 Winter 2013 1 with many thanks to Anya Tafliovich, Gerald Penn, Sheila McIlraith, Wael Aboelsaddat, Tony Bonner, Eric Joanis, Suzanne

More information

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II) Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type. OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compile-time Static 1. Enter expression 2. ML infers a type Exec-time Dynamic Types 3. ML crunches expression down to a value 4. Value

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

So what does studying PL buy me?

So what does studying PL buy me? So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chicken-and-egg. My goal: educate tomorrow s tech leaders

More information

Mini-ML. CS 502 Lecture 2 8/28/08

Mini-ML. CS 502 Lecture 2 8/28/08 Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of

More information

Handout 2 August 25, 2008

Handout 2 August 25, 2008 CS 502: Compiling and Programming Systems Handout 2 August 25, 2008 Project The project you will implement will be a subset of Standard ML called Mini-ML. While Mini- ML shares strong syntactic and semantic

More information

CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point

CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form

More information

Lists. Michael P. Fourman. February 2, 2010

Lists. Michael P. Fourman. February 2, 2010 Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually Plan (next 4 weeks) 1. Fast forward Rapid introduction to what s in OCaml 2. Rewind 3. Slow motion Go over the pieces individually History, Variants Meta Language Designed by Robin Milner @ Edinburgh Language

More information

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

More information

Exercises on ML. Programming Languages. Chanseok Oh

Exercises on ML. Programming Languages. Chanseok Oh Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max

More information

CSE 341 Section 5. Winter 2018

CSE 341 Section 5. Winter 2018 CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records

More information

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012 News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#, Introduction to ML Based on materials by Vitaly Shmatikov slide 1 ML General-purpose, non-c-like, non-oo language Related languages: Haskell, Ocaml, F#, Combination of Lisp and Algol-like features (1958)

More information

A Brief Introduction to Standard ML

A Brief Introduction to Standard ML A Brief Introduction to Standard ML Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Programming Languages

Programming Languages CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes

More information

The type checker will complain that the two branches have different types, one is string and the other is int

The type checker will complain that the two branches have different types, one is string and the other is int 1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"

More information

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1 A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order

More information

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. We are looking for homework graders. If you are interested, send mail to cs242cs.stanford.edu

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD* OCaml 1. Introduction Rapid introduction to what s in OCaml 2. Focus on Features Individually as Needed as Semester Progresses *Notes from Sorin Lerner at UCSD* History, Variants Meta Language Designed

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Data Types The ML Type System

Data Types The ML Type System 7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

Functional Programming

Functional Programming Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

More information

Lecture 2: The Basis of SML

Lecture 2: The Basis of SML Lecture 2: The Basis of SML Jean-Noël Monette Functional Programming 1 September 9, 2013 Based on notes by Pierre Flener, Sven-Olof Nyström Jean-Noël Monette (UU) Lecture 2: The Basis of SML 1 / 73 Today

More information

Programming Languages

Programming Languages CSE 130 : Fall 2008 Programming Languages Lecture 2: A Crash Course in ML Ranjit Jhala UC San Diego News On webpage: Suggested HW #1, sample for Quiz #1 on Thu PA #1 (due next Fri 10/10) No make-up quizzes

More information

Note that pcall can be implemented using futures. That is, instead of. we can use

Note that pcall can be implemented using futures. That is, instead of. we can use Note that pcall can be implemented using futures. That is, instead of (pcall F X Y Z) we can use ((future F) (future X) (future Y) (future Z)) In fact the latter version is actually more parallel execution

More information

Programming Languages

Programming Languages CSE 130: Spring 2010 Programming Languages Lecture 2: A Crash Course in ML Ranjit Jhala UC San Diego News On webpage: Suggested HW #1 PA #1 (due next Wed 4/9) Please post questions to WebCT Today: A crash

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Programming Languages

Programming Languages CSE 130: Fall 2009 Programming Languages Lecture 2: A Crash Course in ML News On webpage: Suggested HW #1 PA #1 (due next Fri 10/9) Technical issues installing Ocaml - should be resolved soon! Ranjit Jhala

More information

Datatype declarations

Datatype declarations Datatype declarations datatype suit = HEARTS DIAMONDS CLUBS SPADES datatype a list = nil (* copy me NOT! *) op :: of a * a list datatype a heap = EHEAP HEAP of a * a heap * a heap type suit val HEARTS

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

More information

CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

More information

Begin at the beginning

Begin at the beginning Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of

More information

Inductive Data Types

Inductive Data Types Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information

Type Checking and Type Inference

Type Checking and Type Inference Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

More information

F28PL1 Programming Languages. Lecture 11: Standard ML 1

F28PL1 Programming Languages. Lecture 11: Standard ML 1 F28PL1 Programming Languages Lecture 11: Standard ML 1 Imperative languages digital computers are concrete realisations of von Neumann machines stored program memory associations between addresses and

More information

CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego CSE 130 Programming Languages Lecture 3: Datatypes Ranjit Jhala UC San Diego News? PA #2 (coming tonight) Ocaml-top issues? Pleas post questions to Piazza Recap: ML s Holy Trinity Expressions (Syntax)

More information

CSC 533: Organization of Programming Languages. Spring 2005

CSC 533: Organization of Programming Languages. Spring 2005 CSC 533: Organization of Programming Languages Spring 2005 Language features and issues variables & bindings data types primitive complex/structured expressions & assignments control structures subprograms

More information

Polymorphism and Type Inference

Polymorphism and Type Inference Polymorphism and Type Inference Volker Stolz stolz@ifi.uio.no INF 3110-2008 Department of Informatics University of Oslo Initially by Gerardo Schneider. Based on John C. Mitchell s slides (Stanford U.)

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

More information

Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1 A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

More information

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language Functional Programming Introduction to COOL #1 Cunning Plan Functional Programming Types Pattern Matching Higher-Order Functions Classroom Object-Oriented Language Methods Attributes Inheritance Method

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL. Chapter 2 - First Steps PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

More information

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks) Any questions Say hello to OCaml? void sort(int arr[], int beg, int end){ if (end > beg + 1){ int piv = arr[beg]; int l = beg + 1; int r = end; while (l!= r-1){ if(arr[l]

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML CMSC 330: Organization of Programming Languages Functional Programming with OCaml 1 Background ML (Meta Language) Univ. of Edinburgh, 1973 Part of a theorem proving system LCF The Logic of Computable Functions

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Standard ML. Data types. ML Datatypes.1

Standard ML. Data types. ML Datatypes.1 Standard ML Data types ML Datatypes.1 Concrete Datatypes The datatype declaration creates new types These are concrete data types, not abstract Concrete datatypes can be inspected - constructed and taken

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

More information

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f

More information

Chapter 3 Linear Structures: Lists

Chapter 3 Linear Structures: Lists Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:

More information

Recap: ML s Holy Trinity

Recap: ML s Holy Trinity Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set

More information

Some Advanced ML Features

Some Advanced ML Features Some Advanced ML Features Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming University of Washington: Dan Grossman ML is small Small number of powerful constructs

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 5: Fundamentals III & ML

Announcements. CSCI 334: Principles of Programming Languages. Lecture 5: Fundamentals III & ML Announcements CSCI 334: Principles of Programming Languages Lecture 5: Fundamentals III & ML Instructor: Dan Barowy Claire Booth Luce info session tonight for women interested in summer research (hopefully

More information

Lecture 12: Data Types (and Some Leftover ML)

Lecture 12: Data Types (and Some Leftover ML) Lecture 12: Data Types (and Some Leftover ML) COMP 524 Programming Language Concepts Stephen Olivier March 3, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goals

More information

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1 A Fourth Look At ML Chapter Eleven Modern Programming Languages, 2nd ed. 1 Type Definitions Predefined, but not primitive in ML: datatype bool = true false; Type constructor for lists: datatype 'element

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

CS321 Languages and Compiler Design I Winter 2012 Lecture 13

CS321 Languages and Compiler Design I Winter 2012 Lecture 13 STATIC SEMANTICS Static Semantics are those aspects of a program s meaning that can be studied at at compile time (i.e., without running the program). Contrasts with Dynamic Semantics, which describe how

More information

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Chapter 3 Linear Structures: Lists

Chapter 3 Linear Structures: Lists Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

More information

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330, Fall 2013, Practice Problem 3 Solutions CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change

More information