1 / 77

A First Look at ML

A First Look at ML. Additional information Programming in ML A Gentle Introduction to ML. Download as Power Point file for saving or printing . Download as Power Point file for saving or printing . Why ML?. Very high level above machine architecture – powerful

thora
Download Presentation

A First Look at ML

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A First Look at ML Additional information • Programming in ML • A Gentle Introduction to ML Download as Power Point file for saving or printing. Download as Power Point file for saving or printing. Modern Programming Languages - Chapter 5

  2. Why ML? • Very high level above machine architecture – powerful • Functional language – everything returns a result • Interactive – code and test immediately • Minimal side effects - easier to reason about program behavior • Native list operations • Pattern matching programming style • Useful for studying fundamentals of languages • Used to implement language interpreter Modern Programming Languages - Chapter 5

  3. Functional Languages • Example: a factorial function in ML • Hallmarks of functional languages: • Single-valued variables • Heavy use of recursion • Functions are first-class citizens, can be used as parameters, function results, etc. • Minimal use of assignments and side-effects fun fact x = if x <= 0 then 1 else x * fact(x-1); Modern Programming Languages - Chapter 5

  4. ML • Meta Language • One of the more popular functional languages along with Lisp and Scheme • Useful in Artificial Intelligence and programming languages. • Edinburgh, 1974, Robin Milner’s group • There are a number of dialects • We are using Standard ML, but we will just call it ML from now on Modern Programming Languages - Chapter 5

  5. Using ML at IUS • Start | Programs | Student Apps | • Network Shortcuts | Poly ML • Enter ML instructions Modern Programming Languages - Chapter 5

  6. Using ML at Home • Unzip and run the Setup • Open by something similar to: Start | Programs | Poly ML | Run | Poly ML • Enter ML instructions Modern Programming Languages - Chapter 5

  7. Programming, Copying and Pasting • Program ML by: • Entering instructions at the > prompt in the execution window for immediate execution. • Enter instructions in Notepad or in ML source editor. Copy and paste into execution window. • Copy from these notes and paste into Poly ML execution window. • Use the Edit | Paste or Ctrl V • Poly ML ignores input when using right-click Paste Modern Programming Languages - Chapter 5

  8. Example 1+2*3 > 1+2*3;val it = 7 : int> 1+2*3# ; val it = 7 : int • Type an expression after > prompt; ML replies with value and type • After the expression put a ;. (The ; is not part of the expression.) • If you forget, the next prompt will be # (= in some ML), meaning that ML expects more input, then type the ;). • Variable it is a special variable bound to expression value typed. Modern Programming Languages - Chapter 5

  9. Outline • Constants • Operators • Defining Variables • Tuples and Lists • Defining Functions • ML Types and Type Annotations Modern Programming Languages - Chapter 5

  10. Number constants 1234;val it = 1234 : int123.4;val it = 123.4 : real • Integer constants: standard decimal , but use tilde for unary negation (such as ~1) • Real constants: standard decimal notation • Note the type names: int, real Modern Programming Languages - Chapter 5

  11. bool constants true;val it = true : boolfalse;val it = false : bool • Boolean constants true and false • ML is case-sensitive: use true, not True or TRUE • Note type name: bool Modern Programming Languages - Chapter 5

  12. char and string constants "fred";val it = "fred" : string"H";val it = "H" : string#"H";val it = #"H" : char • String constants: text inside double quotes • Can use C-style escapes: \n, \t, \\, \", etc. • Character constants: put # before a 1-character string • Note type names: string and char Modern Programming Languages - Chapter 5

  13. Outline • Constants • Operators • Defining Variables • Tuples and Lists • Defining Functions • ML Types and Type Annotations Modern Programming Languages - Chapter 5

  14. Arithmetic ~ 1 + 2 - 3 * 4 div 5 mod 6;val it = ~1 : int~ 1.0 + 2.0 - 3.0 * 4.0 / 5.0;val it = ~1.4 : real • Standard operators for integers, using ~ for unary negationand - for binary subtraction • Same operators for reals, but use / for division • Left associative, precedence is {+,-} < {*,/,div,mod} < {~}. Modern Programming Languages - Chapter 5

  15. Concatenation and Relations "bibity" ^ "bobity" ^ "boo";val it = "bibitybobityboo" : string 2 < 3;val it = true : bool1.0 <= 1.0;val it = true : bool#"d" > #"c";val it = true : bool"abce" >= "abd";val it = false : bool • String concatenation: ^ operator • Ordering comparisons: <, >, <=, >=, apply to string, char, int and real • Order on strings and characters is lexicographic (alphabetic) Modern Programming Languages - Chapter 5

  16. More Relations 1 = 2; val it = false : bool true <> false; val it = true : bool 1.3 = 1.3; Error: operator and operand don't agree [equality type required] operator domain: ''Z * ''Z operand: real * real in expression: 1.3 = 1.3 • Equality comparisons: = and <> • Most types are equality testable: these are equality types • Type real is not an equality type Modern Programming Languages - Chapter 5

  17. bool operators 1 < 2 orelse 3 > 4;val it = true : bool1 < 2 andalso not (3 < 4);val it = false : bool • Boolean operators: andalso, orelse, not. (And we can also use = for equivalence and <> for exclusive or.) • Precedence so far: {orelse} < {andalso} < {=,<>,<,>,<=,>=} < {+,-,^} < {*,/,div,mod} < {~,not} Modern Programming Languages - Chapter 5

  18. Short-circuiting bool operations true orelse 1 div 0 = 0;val it = true : bool • Note: andalsoand orelse are short-circuiting operators: if the first operand of orelse is true, the second is not evaluated; likewise if the first operand of andalso is false. • Technically, they are not ML operators, but keywords. • All true ML operators evaluate all operands. 2*3 < 5; val it = false : bool Modern Programming Languages - Chapter 5

  19. Conditionals if 1 < 2 then " 1 < 2" else "2 < 1";val it = " 1 < 2" : stringif 1 > 2 then 34 else 56;val it = 56 : int(if 1 < 2 then 34 else 56) + 1;val it = 35 : int • Value of the expression is the value of the then part if the test part is true or the value of the else part otherwise • Similar to C's ternary operator: (1<2) ? 'x' : 'y' • Conditional expression (not statement) using if … then … else … • No if … then construct if 1 < 2 then 3;Error: else expected but ; was found Modern Programming Languages - Chapter 5

  20. Exercise 1 What is the value and ML type for each of these expressions? • "abc" ^ "def" ^ “gh" • if (1 < 2) then 3.0 else 4.0; • 5 * (if (1 < 2) then 3 else 4); • 1 < 2 orelse (1 div 0) = 0; What is wrong with each of these expressions? • 10 / 5; • #"a" = #"b" or 1 = 2; • 1.0 = 1.0; • if 1.0 < 2.0 then 3; Modern Programming Languages - Chapter 5

  21. No Implicit type conversion 1 * 2;val it = 2 : int1.0 * 2.0;val it = 2.0 : real1.0 * 2;Error: operator and operand don't agree 1.0 < 2;Error:Can't unify int with real (Different type constructors) • The *, +, < and other integer operators are overloaded to have one meaning on pairs of integers, and another on pairs of reals. • ML does not perform implicit type conversion. Modern Programming Languages - Chapter 5

  22. Explicit type conversion real 123;val it = 123.0 : realfloor 3.6;val it = 3 : intfloor 3.6 < 4;val it = true : boolstr #"a";val it = "a" : string • Builtin conversion functions: real (int to real), floor (real to int), ceil (real to int), round (real to int), trunc (real to int), ord (char to int), chr (int to char), str (char to string) • Apply a function to the argument by: function argument. • For example: floor 3.6; Modern Programming Languages - Chapter 5

  23. Function Associativity • Function application is left-associative • So f a b means (f a) b, which means: • first apply f to the single argument a; • then take the value f returns, which should be another function; • then apply that function to b • For example, chr trunc 97.5should be written as: chr (trunc 97.5) • More on how this can be useful later Modern Programming Languages - Chapter 5

  24. Function application precedence square 2+1; val it = 5 : int square (2+1); val it = 9 : int • Function application has higher precedence than any operator. • Parenthesize to define an explicit precedence. Modern Programming Languages - Chapter 5

  25. Exercise 2 What, if anything, is wrong with each of these expressions? • trunc 5; • ord #"a" + 1; • 5+4.0; • if 0 then 1 else 2; • if true then 1 else 2.0; • chr(trunc(97.0)); • chr(trunc 97.0); • chr trunc 97.0; Modern Programming Languages - Chapter 5

  26. Outline • Constants • Operators • Defining Variables • Tuples and Lists • Defining Functions • ML Types and Type Annotations Modern Programming Languages - Chapter 5

  27. Variable definition val x = 1+2*3;val x = 7 : intx;val it = 7 : intval y = if x = 7 then 1.0 else 2.0;val y = 1.0 : real • Define a new variable and bind to a value using val. • Variable names should consist of a letter, followed by zero or more letters, digits, and/or underscores. Modern Programming Languages - Chapter 5

  28. Multiple Variable Definitions val fred = 23;val fred = 23 : intval fred = true;val fred = true : boolfred;val it = true : bool • Can define a new variable with the same name as an old one, even using a different type. (This is not particularly useful.) • This is not the same as assignment. It defines a new variable but does not change the old one. Any part of the program that was using the first definition of fred, still is after the second definition is made. Modern Programming Languages - Chapter 5

  29. Exercise 3 Suppose we make these ML declarations: val a = "123";val b = "456";val c = a ^ b ^ "789";val a = 3 + 4; Then what is the value and type of each of these expressions? 1) a;2) b;3) c;4) a=6; Modern Programming Languages - Chapter 5

  30. The Inside Story • In interactive mode, the expected input is a sequence of declarations • If you type just an expression exp instead of a declaration, ML treats it as if you had typed: val it =exp; • For example: 5; val it = 5 : int Modern Programming Languages - Chapter 5

  31. Garbage Collection • Sometimes the ML interpreter will print a line like this, for no apparent reason:GC #0.0.0.0.1.3: (0 ms) • This is what ML says when it is performing a “garbage collection”: reclaiming pieces of memory that are no longer being used • We’ll see much more about this when we look at Java. Modern Programming Languages - Chapter 5

  32. Outline • Constants • Operators • Defining Variables • Tuples and Lists • Defining Functions • ML Types and Type Annotations Modern Programming Languages - Chapter 5

  33. Tuples val barney = (1+2, 3.0*4.0, "brown");val barney = (3,12.0,"brown") : int*real*stringval point1 = ("red", (300,200));val point1 = ("red",(300,200)):string*(int*int) #2 barney;val it = 12.0 : real#1 (#2 point1);val it = 300 : int Heterogeneous, tuples can contain other tuples (i.e. mixed types) Parentheses define tuples A tuple is similar to a struct in C++ but with no field names #i x is the i'th element of tuple x. For example:#2 (“red”,50, true);is 50; Modern Programming Languages - Chapter 5

  34. No tuple of one (1, 2); val it = (1,2) : int * int (1); val it = 1 : int #1 (1, 2); val it = 1 : int #1 (1); Error: operator and operand don't agree operator domain: {1:'Y; 'Z} operand: int in expression: (fn {1=1,...} => 1) 1 There is no such thing as a tuple of one Modern Programming Languages - Chapter 5

  35. Tuple Type Constructor • The type of a tuple gives * as a type constructor • For tuple(5,true)int * boolis the type of pairs ( x, y ) where x is an int and y is a bool • Parentheses have structural significance, each below are different: • int * (int * bool) (5,(6, true)) • (int * int) * string ((5,6), “Hi”) • int * int * bool (5, 6, true) • (bool*int)*(int*real) ((true,4),(5,3.1)) Modern Programming Languages - Chapter 5

  36. Exercise 4 What are the values of these expressions? • #2 (3,4,5); • val x = (1+2, 3.0*0.5, "zig" ^ "zag"); • #3 x; • (4,5) = (4,5); What is wrong with the following expressions? • #4 (3,4,5); • (4, "zig") = (4,5); • (4,5.0) = (4,5.0); What is the type? • (3,"zig",5.3); • (3,(4, "zig"),5.3) Modern Programming Languages - Chapter 5

  37. Lists [1,2,3];val it = [1,2,3] : int list[1.0,2.0];val it = [1.0,2.0] : real list[true];val it = [true] : bool list [(1,2),(1,3)];val it = [(1,2),(1,3)] : (int * int) list[[1,2,3],[1,2]]; val it = [[1,2,3],[1,2]] : int list list • Square brackets define lists. • Homogenous, all list elements must be the same type. [1.0,2.0]; real list [(1,2.0),(1,3.2)]; (int * real) list Modern Programming Languages - Chapter 5

  38. Empty list [];val it = [] : 'a listnil;val it = [] : 'a list nil=[]; val it = true : bool Empty list is [] or nil Note the type of the empty list: 'a list Any variable name beginning with an apostrophe is a type variable; it stands for a type that is unknown 'a list means a list of elements, type unknown Modern Programming Languages - Chapter 5

  39. The null test null [];val it = true : boolnull [1,2,3];val it = false : bool • null tests for the empty list • Can use an equality test, as in x = [] • However, null x is preferred; we will see why in a moment Modern Programming Languages - Chapter 5

  40. List Type Constructor • The type list is type constructor • For example: [5,6] the type int list means each element is of type int • A list is not a tuple: [5,6] is not (5,6) Modern Programming Languages - Chapter 5

  41. @ concatenates lists [1,2,3]@[4,5,6];val it = [1,2,3,4,5,6] : int list @ operator concatenates two lists of the same type [5] @ [6,7] result is [5, 6, 7] 5 @ [6, 7] Error, both must be lists [true] @ [6, 7] Error, lists must be same type [(2,"Hel")]@[(3, "lo")]; [(2, "Hel"), (3, “lo")] [(2,"Hel")]@[(3, 5)]; Error, lists not same type Modern Programming Languages - Chapter 5

  42. :: builds lists val n = 5::[6,7]; val it = [5, 6, 7] : int list val x = 5::[]; val x = [5] : int list val y = 6::x;val y = [6,5] : int listval z = 7::y;val z = [7,6,5] : int list :: operator is List-builder (pronounced cons) Constructs new list by appending element to a list :: operator is right-associative 5::6::7::[ ] result is [5, 6, 7] Modern Programming Languages - Chapter 5

  43. hd and tl access list head and tail val z = 1::2::[];val z = [1,2] : int list hd z;val it = 1 : int tl z;val it = [2] : int listtl(tl z);val it = [] : int list The hd function returns the head of a list: the first elementhd [5, 6, 7]; returns 5 The tl function returns the list tail: all but the first elementtl [5, 6, 7]; returns [6, 7] Modern Programming Languages - Chapter 5

  44. Strings: explode and implode explode "hello";val it = [#"h",#"e",#"l",#"l",#"o"] : char listimplode [#"h",#"i"];val it = "hi" : string explodefunction converts a string to a list of characters. implodefunction does the reverse; converts a list of characters to a string. Modern Programming Languages - Chapter 5

  45. What are the values of these expressions? • [1,2]@[3,4]; • 1::2::[]; • [1::2::nil]; • hd(1::2::nil); • hd [[1,2],[3,4]]; • tl [[1,2],[3,4]]; • tl [5]; • hd(tl(#2([1,2],[3,4]))); • hd [(3,4),(5,6)]; • (hd [1,3,4])::2::(tl [1,3,4]); Exercise 5 Modern Programming Languages - Chapter 5

  46. Exercise 5 Continued What is wrong with the following expressions? • hd []; • hd(tl(tl [1,2])); • 1@2; • [1]::[2,3]; • hd 1::2::nil; Modern Programming Languages - Chapter 5

  47. Exercise 5 Continued Give ML to yield the result: • Concatenate [1,2] with [3,4]. • 1 cons’ed to [2,3]. • Second element of [1,2,3,4]. • Last element of [1,2,3,4]. • 2 cons’ed to [1,3] to yield [1,2,3]. Hint: Use 2 statements. Modern Programming Languages - Chapter 5

  48. Outline • Constants • Operators • Defining Variables • Tuples and Lists • Defining Functions • ML Types and Type Annotations Modern Programming Languages - Chapter 5

  49. Function definition fun add (x, y) = x + y;val add = fn : int * int -> int • add –– the function name • (x, y) ––parameter tuple • x + y –– function result • val add=fn : int * int -> int ––Function type Analogous C example int add(int x, int y) { return x + y; } Modern Programming Languages - Chapter 5

  50. fun – function definition fun firstChar str = hd (explode str);val firstChar = fn : string -> char firstChar "abc";val it = #"a" : char fun defines a new function and binds to variable firstChar Type fn means a function. firstChar is a string -> char function whose argument strtype is string and the return type is char Rarely necessary to declare any types, since ML infers them. ML determines that str is a string from explode str.And the function result must be a char from hd (explode str) since result is the hd of a char list Modern Programming Languages - Chapter 5

More Related