Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

SML Programming: Understanding Declarations, Functions, and Pattern Matching, Slides of Computer Science

An introduction to standard ml (sml) programming, focusing on declarations, functions, and pattern matching. It covers the basics of sml syntax, including val and fun declarations, function application, list syntax, case expressions, let expressions, multi-argument functions, tuples, and currying. The document also touches upon the difference between anonymous functions and lambda expressions, as well as the use of case expressions in function definitions.

Typology: Slides

2012/2013

Uploaded on 03/22/2013

dheerandra
dheerandra 🇮🇳

4.3

(38)

146 documents

1 / 45

Toggle sidebar

Related documents


Partial preview of the text

Download SML Programming: Understanding Declarations, Functions, and Pattern Matching and more Slides Computer Science in PDF only on Docsity! Lecture #2, Jan. 10, 2007 •Evaluating expressions •Defining functions •Case exp •Let exp •Exceptions •Defining new data and constructors •Pattern matching over constructors •Binary Search trees •Expressions •Tokens •Simple Lexer •Common errors. Docsity.com More on SML • We have a lot to learn about SML • Well will go over some high level stuff today • We also have the three lab sessions. I hope everyone can attend at least one of the sessions. – FAB INTEL Lab (FAB 55-17) downstairs by the Engineering and Technology Manangement’s departmental offices – Friday Jan. 12, 2007. 4:00 – 5:30 PM – Tueday Jan. 16, 2007 4:00 – 5:30 – Friday Jan. 19, 2005. 4:00 – 5:30 PM Docsity.com Functions • Functions are usually defined in Files and loaded into to SML. Example: – use “lect01.sml” • Predefined Functions on numbers – Type of numbers: int and real – overloaded operators +, *, - , / , mod – Conversion functions: floor, ceiling, trunc, round • Predefined Functions on Booleans – Relational operators < > <= >= = != – Combinators andalso orelse – Examples - 5 > 7 false - 1==4 false Docsity.com Finding type of functions - length val it = fn : 'a list -> int - - op @; val it = fn : 'a list * 'a list -> 'a list - - rev; val it = fn : 'a list -> 'a list - - op +; val it = fn : int * int -> int Docsity.com Defining and using Functions • Defined by writing equations (sometimes more than 1) • By Declaration: fun plusone x = x+1; • By Lambda expression: fn x => x + 1 – These are anonymous functions, and are probably new to you. Don’t let them scare you. • Application by juxtaposition (no parenthesis needed) • plusone 8 • (fn x => x + 1) 8 Docsity.com Using case in fun definition • The case expression uses patterns fun length(y) = case y of [] => 0 | (x :: xs) => 1 + (length xs) • In the pattern: (x :: xs) – x, stands for the hd(y) – xs, stands for the tl(y) • Much more about patterns later in the lecture! Docsity.com Let expressions • Let expressions allow programmers to make local declaration for both values and functions. val ex2 = let val x = 34 fun f x = x - 3 in f x - 4 end; Multiple declarations allowed, both “val” and “fun”, no separators necessary The scope of the new declarations is the expression between the key words “in” and “end” Docsity.com Multi Argument functions: Tuples • Functions of more than 1 argument: • tuples • currying • fun evenprod (x,y) = even(x * y); • fun evenprod x y = even(x * y); • Conditional Expressions: If • fun minpair (x,y) = if x < y then x else y; Docsity.com Bindings, and recursive scope: val x = 12; fun f x = x + 2; fun g y = x + 2; • fun bindings are just like val bindings val f = (fn x => x + 2); • But NOT RECURSIVE PROGRAMS! why? fun plus x y = if x = 0 then y else 1 + (plus (x-1) y); val rec plus = fn x => fn y => if x = 0 then y else 1 + (plus (x-1) y); this is an anonymous function, often called a lambda expression Docsity.com Pattern Matching Definitions: fun and true false = false | and true true = true | and false false = false | and false true = false; • (ORDER MATTERS) • Variables in Patterns: fun and true true = true | and x y = false Note that “and” has more than 1 equation. Docsity.com Rules for patterns: • Patterns has only Constructors, (true, false, :: ) variables (x, y, z) , and constants (3, “red”). • All the patterns (on the left) should have compatible types • The cases should be exhaustive • There should be no ambiguity as to which case applies. (Ordering fixes ambiguity if there is any) Docsity.com Taking Lists Apart ? hd [1,2,3] 1 ? tl [1,2,3] [2, 3] ? List.take ([1,2,3],2) [1,2] ? List.drop ([1,2,3],2) [3] Docsity.com Cons (::) and [ ] are enough • [1,2,3] -> 1 :: (2 :: (3 :: [ ])) • If the infix operator (::) is right associative • 1 :: 2 :: 3 :: [ ] • All lists are constructed in one of two ways • [ ] or • (x :: xs) for some element x and list xs Docsity.com More about patterns • Patterns can be nested • Patterns can have wild-cards fun double y = case y of (a :: (b :: [])) => true | _ => false • Special syntax for list Patterns fun exactlytwo x = Case x of [] => false | [x] => false | [x,y] => true | (x :: xs) => false; These features can be used in “fun” declarations with multiple clauses as well as in “case” expressions! Docsity.com Constant Constructors • Constant constructors are constant • Can be allocated once at compile-time. • Like constant pointers that never change. • The nil constructor [] for lists is an example. Docsity.com Constructor Functions • Constructor functions allocate in the heap. • Each constructor may allocate a different amount of memory • If we had to do this in C we might write list cons (void * hd, list tl) { list Block = (list) malloc (sizeof (struct listStruct)); Block->Tag = consTag; Block->Data.consData.hd = hd; Block->Data.consData.tl = tl; return (Block); }; • In ML this is done automatically. Docsity.com Introducing new data and constructors datatype Tree = Tip | Node of Tree * int * Tree; val tree1 = Node(Node(Tip,4,Tip) ,7 ,Node(Tip,10,Tip)); Constant constructor, contains no data Constructor function. Contains 3 fields. The function Node takes a triple with 3 components. The “of” keyword is used for constructor functions 7 4 10 Docsity.com Example Expressions datatype Exp = Const of int | Add of Exp * Exp | Mult of Exp * Exp | Sub of Exp * Exp; val exp1 = Add(Const 4,Const 3); (* 4+3 *) val exp2 = Mult(exp1,exp1); (* (4+3)*(4+3) *) Docsity.com Pattern matching functions fun ExpValue (Const n) = n | ExpValue (Add(x,y)) = ExpValue x + ExpValue y | ExpValue (Mult(x,y)) = ExpValue x * ExpValue y | ExpValue (Sub(x,y)) = ExpValue x - ExpValue y; Docsity.com Review • New data structures are introduced by the datatype declaration (like Tree, Exp, and Token). • A datatype declaration introduces – constructor constants (Tip, and [] ) – constructor functions (Node, Add, Mult) • every time one of these is applied some memory is automatically allocated in the heap. • Functions consuming these data structures make choices by using pattern matching written using equations Docsity.com Lexer helper functions fun extend x (xs, cs) = ((x::xs), cs); (* ident: char -> char list -> (Token * char list) *) fun ident c cs = let fun help x [] = ([x],[]) | help x (c::cs) = if Char.isAlpha c then extend x Make an Id token Collect a prefix which is all alpha, and the rest of the list. Help returns a pair Add a char to the first component of the pair Docsity.com More help (* literal: char -> char list -> (Token * char list) *) fun literal c cs = let fun help x [] = ([x],cs) | help x (c::cs) = if Char.isDigit c then extend x (help c cs) else ([x],c :: cs) val (lexeme,rest) = help c cs in case Int.fromString (String.implode lexeme) of NONE => (Illegal,rest) | SOME n => (Int n,rest) end; datatype ‘a option = NONE | SOME of ‘a; Turn the list of Char into a string, then use the library function to turn the string into an int. The translation may fail, see datatype option. Docsity.com Common Errors • Forgetting the “of” in the type of a constructor function: datatype Trans = Trans Start * Label * Finish; S02code.sml:129.24 Error: syntax error: inserting INFIX Docsity.com Bad patterns - fun length [] = 0 | length x :: xs = 1 + length xs; std_in:26.14-26.15 Error: NONfix pattern required std_in:25.5-26.34 Error: clauses don't all have same number of patterns std_in:25.5-26.34 Error: data constructor :: used without argument in pattern std_in:25.1-26.34 Error: rules don't agree (tycon mismatch) expected: 'Z list -> int found: 'Y * 'X * 'W -> int rule: (x,_,xs) => + : overloaded (1,length xs) - fun length [] = 0 | length (x::xs) = 1 + length xs; val length = fn : 'a list -> int Docsity.com Look closely at the types! - fun appendall [] = [] | appendall (x::xs) = x :: (appendall xs); val appendall = fn : 'a list -> 'a list (* OOPs the wrong type *) - fun appendall [] = [] | appendall (x::xs) = x @(appendall xs); val appendall = fn : 'a list list -> 'a list Docsity.com The missing “end” bug fun e n = let val seq = 0 upto n fun term x = 1.0 / (real (fact x)) in term; /tmp/sml.tmp.o29014:5.9 Error: syntax error found at EOF Docsity.com
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved