Programovací jazyky F# a OCaml Chapter 3. Composing primitive types into data.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Programovací jazyky F# a OCaml Chapter 4. Generic and recursive types.
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Programovací jazyky F# a OCaml Chapter 2. Refactoring code using functions.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Describing Process Specifications and Structured Decisions Systems Analysis and Design, 7e Kendall & Kendall 9 © 2008 Pearson Prentice Hall.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Chapter 2 storing numbers and creating objects Pages in Horstmann.
CSE S. Tanimoto Syntax and Types 1 Representation, Syntax, Paradigms, Types Representation Formal Syntax Paradigms Data Types Type Inference.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
CSE 341, S. Tanimoto Concepts 1- 1 Programming Language Concepts Formal Syntax Paradigms Data Types Polymorphism.
Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 2 - Algorithms and Design
Input, Output, and Processing
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Lexical Analysis I Specifying Tokens Lecture 2 CS 4318/5531 Spring 2010 Apan Qasem Texas State University *some slides adopted from Cooper and Torczon.
Flow of Control Part 1: Selection
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Applications Development
Regular Expressions Chapter 6 1. Regular Languages Regular Language Regular Expression Finite State Machine L Accepts 2.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Programovací jazyky F# a OCaml Chapter 6. Sequence expressions and computation expressions (aka monads)
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
LECTURE 10 Semantic Analysis. REVIEW So far, we’ve covered the following: Compilation methods: compilation vs. interpretation. The overall compilation.
Structures, Unions, Enumerations
Computing and Statistical Data Analysis Lecture 2
Theory of Computation Lecture 4: Programs and Computable Functions II
Representation, Syntax, Paradigms, Types
Expanded Recursive Diagrams OCAML rapid tour, day 2
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
CNG 140 C Programming (Lecture set 10)
PROGRAMMING IN HASKELL
More Selections BIS1523 – Lecture 9.
Higher-Order Procedures
The Metacircular Evaluator
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
PROGRAMMING IN HASKELL
Representation, Syntax, Paradigms, Types
4. Dividing Computing with Pattern Matching in F#
Type & Typeclass Syntax in function
Representation, Syntax, Paradigms, Types
The Metacircular Evaluator (Continued)
Representation, Syntax, Paradigms, Types
6.001 SICP Interpretation Parts of an interpreter
Theory of Computation Lecture 4: Programs and Computable Functions II
Review Previously User-defined data types: records, variants
Presentation transcript:

Programovací jazyky F# a OCaml Chapter 3. Composing primitive types into data

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »We can think of data type as a set: More complicated with other types, but possible… »Functions are maps between sets (math!) For example, the function: f : X -> Y f(x) = y assigns value y ∈ Y to any x ∈ X Functions is undefined for x ∈ X Keeps looping forever or throws an exception Data types

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Functions are arrows between different types »Higher-order functions Tricky – we also need type for functions »Multi-argument functions Are higher-order too Drawing functions as diagrams

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Identify the key input/output of a function »Relations with mathematics: category theory Diagrams are still useful!

Composing data types

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Product: »Sum: »Some examples: int × char = { … (-1, a), (0, a), … (-1, b), (0, b) … } int ∪ char = { … -1, 0, 1, … a, b, … } int + char = { … (1, -1), (1, 0), (1, 1), … (2, a), (2, b), … } » Constructing complex types in F# Two options: Product types and Sum types Operations with sets How can we distinguish between int and char? tag

Product types in F#

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Store several values of possibly different types The number is known at compile time »We can use pattern matching without match! Tuple type (product) > let resolution = (1600, 1200);; val resolution : int * int = (1600, 1200) > fst resolution;; val it : int = 1600 > match resolution with | (width, height) -> width * height;; val it : int = Two values of type int (one value of int × int) fst and snd return components of two- component tuple Decomposing tuple using pattern matching pattern

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Pattern matching in let binding »The match construct is still important! Pattern matching for tuples > let (width, height) = resolution;; val width : int = 1600 val height : int = 1200 > let num, str = 12, "hello";; val str : string = "hello" val num : int = 12 pattern > match resolution with | (w, h) when float h / float w "widescreen" | (w, h) when float h / float w = > "standard" | _ -> "unknown";; val it : string = "standard" We can omit parenthesis! Binding multiple values

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Using tuples as return values or parameters Computation is written as an expression We need expressions that return more values! »Tuples as arguments - looks like standard call! Tuples as parameters > let divMod tuple = let (a, b) = tuple (a / b, a % b);; val divMod : int * int -> int * int > let divMod (a, b) = (a / b, a % b);; val divMod : int * int -> int * int pattern > let d, rem = divMod (17, 3);; val rem : int = 2 val d : int = 5 Note the difference: int -> int -> int * int int * int -> int * int

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Combine multiple values (set product) Expressions that calculate multiple values Specifying parameters of functions Grouping logically related parameters Example: X and Y coordinates, day + month + year »Very simple data type No information about elements (only types) Avoid using too complex tuples Tuples

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Type with multiple named fields Type needs to be declared in advance Record type (also product) open System type Lecture = { Name : string Room : string Starts : DateTime } let fsharp = { Name = "F# and OCaml" Room = "S11" Starts = DateTime.Parse (" :00") } Type declaration Specify values (type is inferred!) > fsharp.Name;; val it : string = F# and OCaml > match fsharp with | { Name = nm; Room = rm } -> printfn "%s in %s" nm rm;; F# and OCaml in S11 Accessing field by name Decomposing using pattern

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Records (tuples, …) are all immutable How to change schedule of a lecture? Calculate new value of the schedule »Cloning record with some change is common Calculating with records let changeRoom room lecture = { Name = lecture.Name; Starts = lecture.Starts Room = room } let newfs changeRoom "S8" fsharp let changeRoom room lecture = { lecture with Room = room } Copy fields that don’t change Specify new value

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Used for more complex data structures Fields describe the meaning of the code Easy to clone using the with keyword »Tuples store values, Records store data Data – the primary thing program works with Values – result of an expression (intuitive difference!) »In F#, compiled as.NET classes Can be easily accessed from C# Records

Sum types in F#

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Data type that represents alternatives int + string = { …, (1, -1), (1, 0), (1, 1), … …, (2, ""), (2, "a"), (2, "aa"), … } »More examples: Discriminated union (Sum) type Variant = | Int of int | String of string type Season = | Spring | Summer | Autumn | Winter Simplified example – union cases do not carry any values type Shape = | Circle of int | Rect of int * int Using tuple as the carried value

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Distinguishing between cases using patterns »Compile-time checking of patterns »Pattern matching using let: Working with unions let shapeArea shape = match shape with | Circle(radius) -> Math.PI * (pown radius 2) | Rectangle(width, height) -> width * height Discriminator Nested pattern: extracts values match var with | String(msg) -> printfn "%s" msg Warning: Incomplete pattern match let (Int(num)) = var Syntactically correct, but rarely useful

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Used to represent value with different cases Expression evaluates and returns A or B The compiler verifies that we handle all cases Single-case unions are sometimes used »Similar to class hierarchies in OOP We can more easily add new functions Adding new cases requires modifying all functions Discriminated unions

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »We used “sum” of sets to model discriminated unions and “product” to model tuples: »How can we use this operations to construct mathematical model of the following types: Homework #1 type Season = | Spring | Summer | Autumn | Winter type Shape = | Circle of int | Rectangle of int * int

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Represent a value or an empty value Mathematically: add missing value int + {⏊} F# option type let opt = Some(42) match opt with | Some(n) -> printfn "%d" n | None -> printfn "nothing";; // Prints: 42 > let square opt = match opt with | Some(n) -> Some(n * n) | None -> None;; val square : int option -> int option > square (Some 4);; val it : int option = Some 16 > square None;; val it : int option = None Takes and returns “int option” Correct handling of empty values

Pattern matching

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Combining tuples and unions Representing complex data type Color = | Red | White | Blue type VehicleType = | Bicycle // no additional information | Car of int * int // #doors * horses | Motorcycle of int // motor ccm type Vehicle = Color * string * VehicleType Type alias for tuple (we could use records too) We could use System.Drawing.Color Type of vehicle with specific properties

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Other uses: simplification or symbolic differentiation of an expression, compilation Pattern matching match vehicle with | Red, name, _ when name.StartsWith("S") -> printfn "some red S..... vehicle" | _, "Mazda", Car(5, h) when h > 100 -> printfn "5-door Mazda with >100 horses" | White, _, Bicycle | White, _, Motorcycle(_) -> printfn "white bicycle or motorcycle" | _, _, (Car(5, _) & Car(_, 200)) -> printfn "car with 5 doors and 200 horses" | _, _, (Car(_, _) as veh) -> printfn "car: %A" veh when clause nested pattern or pattern and pattern alias pattern

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Write a function that compares two vehicles and prints detailed information about the more expensive one. 1.Motorcycle is always more expensive than bicycle 2.White bicycles are more expensive than other bicycles 3.Car is always more expensive than motorcycle (with the exception of Trabant which is cheaper than motorcycles with engine more than 100ccm) 4.The more ccm engine a motorcycle has the better 5.Ferrari and Porsche are more expensive than any other cars (when comparing Ferraris with Porches, the rule 6 applies) 6.The more horses car has the better (if horsepower equals, the more doors it has the better) Bonus point: if you’ll handle all cases when the first vehicle is more expensive than the second in one match clause Homework #2