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

Similar documents
Java Object Oriented Design. CSC207 Fall 2014

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

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

Informatics 1 Functional Programming Lecture 9. Algebraic Data Types. Don Sannella University of Edinburgh

Typed Racket: Racket with Static Types

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

Algebraic Types. Chapter 14 of Thompson

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

Ruby: Introduction, Basics

CMSC 330: Organization of Programming Languages. OCaml Data Types

CSCI-GA Scripting Languages

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Programming Languages and Techniques (CIS120)

Why OCaml? Introduction to Objective Caml. Features of OCaml. Applications written in OCaml. Stefan Wehr

Introduction to Objective Caml

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

Ruby: Objects and Dynamic Types

Question 2. [5 points] Given the following symbolic constant definition

61A Lecture 2. Friday, August 28, 2015

CMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)

Lexical and Syntax Analysis. Abstract Syntax

The Typed Racket Guide

We will start our journey into Processing with creating static images using commands available in Processing:

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

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

Products and Records

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

An introduction introduction to functional functional programming programming using usin Haskell

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Quick Review of Object-Oriented Programming in Go

Example: Haskell algebraic data types (1)

CS 360: Programming Languages Lecture 10: Introduction to Haskell

2. [20] Suppose we start declaring a Rectangle class as follows:

Inductive Data Types

CS 360: Programming Languages Lecture 12: More Haskell

CMSC 330: Organization of Programming Languages

61A Lecture 2. Wednesday, September 4, 2013

CISC 1600 Lecture 3.1 Introduction to Processing

CS/ENGRD 2110 SPRING 2018

egrapher Language Reference Manual

G Programming Languages - Fall 2012

Typed Scheme: Scheme with Static Types

Object-Oriented Programming Concepts

9/19/12. Why Study Discrete Math? What is discrete? Sets (Rosen, Chapter 2) can be described by discrete math TOPICS

c.def (pronounced SEE-def) Language Reference Manual

CMSC 132: Object-Oriented Programming II

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

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

CISC 1600, Lab 2.2: Interactivity in Processing

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

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

Homework 1 Due Tuesday, January 30, 2018 at 8pm

ITT8060: Advanced Programming (in F#)

Java Application Development

CS 1302 Chapter 9 (Review) Object & Classes

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Introduction to OCaml

OCaml Style Guide Fall 2017

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Introduction to Java Applications

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

Lab 9: Creating a Reusable Class

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Standard ML. Data types. ML Datatypes.1

Lexical and Syntax Analysis

Programovací jazyky F# a OCaml. Chapter 5. Hiding recursion using function-as-values

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Use of scanf. scanf("%d", &number);

Lecture: Functional Programming

Exploring Processing

An Introduction to Processing

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

CS558 Programming Languages

index.pdf January 21,

Fast Introduction to Object Oriented Programming and C++

Intro. Scheme Basics. scm> 5 5. scm>

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CMSC 330: Organization of Programming Languages

Tool-assisted spec development

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

ECE 122. Engineering Problem Solving with Java

INF121: Functional Algorithmic and Programming

Tomas Petricek. F# Language Overview

ITI Introduction to Computing II

More on functional programming

ITI Introduction to Computing II

QUIZ Lesson 4. Exercise 4: Write an if statement that assigns the value of x to the variable y if x is in between 1 and 20, otherwise y is unchanged.

Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November Type Classes. Don Sannella University of Edinburgh

Input And Output of C++

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS558 Programming Languages

Use the scantron sheet to enter the answer to questions (pages 1-6)

CS 251 Intermediate Programming Methods and More

INTRODUCTION TO HASKELL

CpSc 1111 Lab 4 Formatting and Flow Control

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

Transcription:

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

Data types» We can think of data type as a set: int = -2, -1, 0, 1, 2, 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 unde ined for x X Keeps looping forever or throws an exception

Drawing functions as diagrams» Functions are arrows between different types» Higher-order functions Tricky we also need type for functions» Multi-argument functions Are higher-order too

Diagrams are still useful!» Identify the key input/output of a function int SomeData2 RequiredOutput SomeData1 ProgramInput How to get there?» Relations with mathematics: category theory

Composing data types

Operations with sets» Product:» Sum: = (, ) + = (1, ) (2, )» Some examples: int char = (-1, a), (0, a), (-1, b), (0, b) int char = -1, 0, 1, a, b, How can we distinguish between int and char? int+ char = (1, -1), (1, 0), (1, 1), (2, a), (2, b),» Constructing complex types in F# Two options: Product types and Sum types tag

Product types in F#

Tuple type (product)» Store several values of possibly different types pattern The number is known at compile time Two values of type int > let resolution = (1600, 1200);; (one value of int int) val resolution : int * int = (1600, 1200) > fst resolution;; val it : int = 1600 fstand sndreturn components of twocomponent tuple > match resolution with (width, height) -> width * height;; val it : int = 1920000 Decomposing tuple using pattern matching» We can use pattern matching without match!

Pattern matching for tuples» Pattern matching in let binding > let (width, height) = resolution;; val width : int = 1600 val height : int = 1200 pattern > let num, str = 12, "hello";; val str : string = "hello" val num : int = 12 We can omit parenthesis! Binding multiple values» The match construct is still important! > match resolution with (w, h) when float h / float w < 0.75 -> "widescreen" (w, h) when float h / float w = 0.75 -> "standard" _ -> "unknown";; val it : string = "standard"

Tuples as parameters» Using tuples as return values or parameters Computation is written as an expression We need expressions that return more values! > let divmod tuple (a, b) = = pattern let (a /(a, b, b) a % = b);; tuple val (a divmod / b, : a int % b);; * int -> int * int val divmod : int * int -> int * int» Tuples as arguments - looks like standard call! > 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

Tuples» 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

Record type (also product)» Type with multiple named fields Type needs to be declared in advance open System type Lecture = { Name : string Room : string Starts : DateTime } Type declaration > fsharp.name;; Accessing field by name val it : string = F# and OCaml Specify values (type is inferred!) let fsharp = { Name = "F# and OCaml" Room = "S11" Starts = DateTime.Parse ("5.10.2009 14:00") } Decomposing using pattern > match fsharp with { Name = nm; Room = rm } -> printfn "%s in %s" nm rm;; F# and OCaml in S11

Calculating with records» Records (tuples, ) are all immutable How to change schedule of a lecture? Calculate new value of the schedule Copy fields that don t change let changeroom room lecture = { Name = lecture.name; Starts = lecture.starts Room = room } Specify new value let newfs changeroom "S8" fsharp» Cloning record with some change is common let changeroom room lecture = { lecture with Room = room }

Records» 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#

Sum types in F#

Discriminated union (Sum)» Data type that represents alternatives type Variant = Int of int String of string» More examples: type Season = Spring Summer Autumn Winter Simplified example union cases do not carry any values int+ string = {, (1, -1), (1, 0), (1, 1),, (2, ""), (2, "a"), (2, "aa"), } type Shape = Circle of int Rect of int * int Using tuple as the carried value

Working with unions» Distinguishing between cases using patterns let shapearea shape = match shape with Circle(radius) -> Math.PI * (pown radius 2) Rectangle(width, height) -> width * height Discriminator» Compile-time checking of patterns match var with String(msg) -> printfn "%s" msg» Pattern matching using let: let (Int(num)) = var Nested pattern: extracts values Warning: Incomplete pattern match Syntactically correct, but rarely useful

Discriminated unions» 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

Homework #1» We used sum of sets to model discriminated unions and product to model tuples: + = (1, ) (2, ) = (, )» How can we use this operations to construct mathematical model of the following types: type Season = Spring Summer Autumn Winter type Shape = Circle of int Rectangle of int * int

F# option type» Represent a value or an empty value Mathematically: add missing value int + { } let opt = Some(42) match opt with Some(n) -> printfn "%d" n None -> printfn "nothing";; // Prints: 42 Correct handling of empty values > 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

Pattern matching

Representing complex data» Combining tuples and unions type Color = Red White Blue We could use System.Drawing.Color Type of vehicle with specific properties 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)

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 when clause or pattern 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 alias pattern nested pattern and pattern» Other uses:simplification or symbolic differentiation of an expression, compilation

Homework #2» 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 ccmengine 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