Functional programming in F#: Data Structures

Похожие документы
A.A. 2006/2007 Laurea di Ingegneria Informatica. Fondamenti di C++ Horstmann Capitolo 3: Oggetti Revisione Prof. M. Angelaccio

College Algebra. Logarithms: Denitions and Domains. Dr. Nguyen November 9, Department of Mathematics UK

Question 1: introduction to computer programming

Finite Model Theory / Descriptive Complexity: bin

WEB OF SCIENCE. COVERAGE: multidisciplinary TIME RANGE: DOCUMENT TYPES: articles, proceedings papers, books

Single-rate three-color marker (srtcm)

UNIVERSITÀ DEGLI STUDI DI TORINO

REGISTRATION GUIDE TO RESHELL SOFTWARE

Resources and Tools for Bibliographic Research. Search & Find Using Library Catalogues

Copyright 2012 Binary System srl Piacenza ITALIA Via Coppalati, 6 P.IVA info@binarysystem.eu

Capitolo 5 - Funzioni

Graphs: Cycles. Tecniche di Programmazione A.A. 2012/2013

Introduction. The Structure of a Compiler

Si faccia riferimento all Allegato A - OPS 2016, problema ricorrente REGOLE E DEDUZIONI, pagina 2.

WELCOME UNIPA REGISTRATION:

UNIVERSITÀ DEGLI STUDI DI TORINO

Online Resource 12: Dataset

Ammissibilità di co.co.co. e AdR in H2020. Laura Fulci Dirigente Area Ricerca Politecnico di Torino

Combinazioni serie HL-MHL + MHL. Sono disponibili varie combinazioni tra e riduttori coassiali serie MHL (2 stadio).

Quando mi collego ad alcuni servizi hosting ricevo un messaggio relativo al certificato di protezione del sito SSL, come mai?

REGISTRATION. Area Ricerca

SRT064 BTH SRT051 BTH SRT052 BTH

Stored Procedures. Massimo Mecella Dipartimento di Ingegneria informatica automatica e gestionale Antonio Ruberti Sapienza Università di Roma

Technical Guidelines GON % Italian production. sports car oriented

PROTOCOLLO DI COMUNICAZIONE MODBUS MODBUS COMMUNICATION PROTOCOL. MANUALE ISTRUZIONI / INSTRUCTION MANUAL IM163-IU v0.61

SVITOL. brand identity guidelines. Indice. Il logo The logo. Interazione con altri elementi grafici Use with other graphic elements

TNCguide OEM Informativa sull introduzione di documentazione aggiuntiva nella TNCguide

Scheda Allarmi Alarm Board MiniHi

NATIONAL SPORT SCHOOL

Capitolo 6 - Array. Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

EML-16 EML-16. Pulses concentrator. Concentratore impulsi MODBUS COMMUNICATION PROTOCOL PROTOCOLLO DI COMUNICAZIONE MODBUS

Session Description Protocol

Mounting the allocator on the heater. Montaggio del ripartitore sul radiatore

FISE Federazione Italiana Sport Equestri

AVERE 30 ANNI E VIVERE CON LA MAMMA BIBLIOTECA BIETTI ITALIAN EDITION

LA SACRA BIBBIA: OSSIA L'ANTICO E IL NUOVO TESTAMENTO VERSIONE RIVEDUTA BY GIOVANNI LUZZI

CILINDRI IDRAULICI HYDRAULIC CYLINDERS

Транскрипт:

Programmazione Avanzata Corso di Laurea in Informatica (L31) Scuola di Scienze e Tecnologie 31 / 51

Summary of previous lectures In the previous lecture we have... : introduced basic principles of programming paradigms; introduced basic concept of a functional language, F#: elementary types; expressions; function definitions; type inference; lists. 32 / 51

Exercises: solutions Ex. 1: Write a function that given in input a and b computes their mcd. 33 / 51

Exercises: solutions Ex. 1: Write a function that given in input a and b computes their mcd. l e t mcd ( a : u i n t 3 2 ) ( b : u i n t 3 2 ) = l e t r e c mcd x y = i f y=0u then x e l s e mcd y ( x%y ) i n mcd ( max a b ) ( min a b ) 33 / 51

Exercises: solutions Ex. 2: Write a function that given in input n returns true if n is a prime number and false otherwise: 34 / 51

Exercises: solutions Ex. 2: Write a function that given in input n returns true if n is a prime number and false otherwise: l e t i s P r i m e n = l e t l i m i t = i n t ( s q r t ( f l o a t ( n ) ) )+1 l e t r e c t e s t n x = i f x>=l i m i t then t r u e e l s e i f n%x = 0 then f a l s e e l s e t e s t n ( x+1) i n t e s t n 2 34 / 51

Exercises: solutions Ex. 3: Write a function that given in input an integer n computes the list of its prime factors. 35 / 51

Exercises: solutions Ex. 3: Write a function that given in input an integer n computes the list of its prime factors. l e t p r i m e F a c t o r s n = l e t r e c divp x y = i f x%y<>0 then ( x, 0 ) e l s e l e t ( z, p ) = divp ( x/y ) y i n ( z, p+1) l e t r e c combp x y = i f x<2 then [ ] e l s e match divp x y with (, 0 ) > combp x ( y+1) ( z, p ) > y : : ( combp z ( y+1) ) i n combp n 2 35 / 51

Imperative statements To simplify coding, standard imperative statements are often included in functional languages. 36 / 51

Imperative statements To simplify coding, standard imperative statements are often included in functional languages. You can use the keyword mutable to specify a variable that can be changed. 36 / 51

Imperative statements To simplify coding, standard imperative statements are often included in functional languages. You can use the keyword mutable to specify a variable that can be changed. l e t mutable x = 1 // d e c l a r a t i o n x < x + 1 // a s s i g n m e n t 36 / 51

Imperative statements To simplify coding, standard imperative statements are often included in functional languages. You can use the keyword mutable to specify a variable that can be changed. l e t mutable x = 1 // d e c l a r a t i o n x < x + 1 // a s s i g n m e n t Mutable variables in F# should generally have a limited scope, either as a field of a type or as a local value. 36 / 51

Imperative statements To simplify coding, standard imperative statements are often included in functional languages. You can use the keyword mutable to specify a variable that can be changed. l e t mutable x = 1 // d e c l a r a t i o n x < x + 1 // a s s i g n m e n t Mutable variables in F# should generally have a limited scope, either as a field of a type or as a local value. Use of mutable variables may introduce side effects! 36 / 51

Imperative statements To simplify coding, standard imperative statements are often included in functional languages. You can use the keyword mutable to specify a variable that can be changed. l e t mutable x = 1 // d e c l a r a t i o n x < x + 1 // a s s i g n m e n t Mutable variables in F# should generally have a limited scope, either as a field of a type or as a local value. Use of mutable variables may introduce side effects! l e t mutable c o u n t e r = 0 l e t s t e p ( ) = x < x +1; x 36 / 51

Loop expressions... The for... to expression is used to iterate in a loop over a range of values of a loop variable: f o r i d e n t i f i e r = s t a r t [ to downto ] f i n i s h do body e x p r e s s i o n 37 / 51

Loop expressions... The for... to expression is used to iterate in a loop over a range of values of a loop variable: f o r i d e n t i f i e r = s t a r t [ to downto ] f i n i s h do body e x p r e s s i o n The while... do expression is used to perform iterative execution (looping) while a specified test condition is true: w h i l e t e s t e x p r e s s i o n do body e x p r e s s i o n 37 / 51

Examples: list of prime factors... l e t p r i m e F a c t o r s 2 n = l e t compp x y = l e t mutable count = 0 l e t mutable v = x w h i l e v%y = 0 do v < v/y count < count+1 ( v, count ) l e t mutable v = n l e t mutable count = 2 l e t mutable r e s = [ ] w h i l e v >= 2 do l e t ( r, p ) = divp v count v < r ; i f p>0 then r e s < count : : r e s ; count < count +1; r e s 38 / 51

Custom data type: Records... Records represent simple aggregates of named values 39 / 51

Custom data type: Records... Records represent simple aggregates of named values t y p e typename = { [ mutable ] l a b e l 1 : type1 ; [ mutable ] l a b e l 2 : type2 ;... } 39 / 51

Custom data type: Records... Records represent simple aggregates of named values t y p e typename = { [ mutable ] l a b e l 1 : type1 ; [ mutable ] l a b e l 2 : type2 ;... } Example: t y p e MyPoint = { x : f l o a t ; y : f l o a t } 39 / 51

Custom data type: Records... Records represent simple aggregates of named values t y p e typename = { [ mutable ] l a b e l 1 : type1 ; [ mutable ] l a b e l 2 : type2 ;... } Example: t y p e MyPoint = { x : f l o a t ; y : f l o a t } You can initialize records by using the labels that are defined in the record: l e t p = { x =10.0 ; y =10.0 } 39 / 51

Custom data type: Records... Fields in a record are accessible via the standard name. field notation: 40 / 51

Custom data type: Records... Fields in a record are accessible via the standard name. field notation: l e t d i s t a n c e p1 p2 = ( ( p1. x p2. x ) 2.0+( p1. y p2. y ) 2. 0 ) 0.5 40 / 51

Custom data type: Records... Fields in a record are accessible via the standard name. field notation: l e t d i s t a n c e p1 p2 = ( ( p1. x p2. x ) 2.0+( p1. y p2. y ) 2. 0 ) 0.5 Records can be used with pattern matching. You can specify some fields explicitly and provide variables for other fields: l e t p o i n t I n f o p = match p with { x =0.0 ; y =0.0 } > p r i n t f This i s the o r i g i n! { x =0.0 ; y= } > p r i n t f This p o i n t i s l o c a t e d on the x a x e s! { x= ; y =0.0 } > p r i n t f This p o i n t i s l o c a t e d on the y a x e s! { x=x v a l ; y=y v a l } > p r i n t f This p o i n t i s l o c a t e d at (%f,% f ) x v a l y v a l 40 / 51

Custom data type: Discriminated Unions... Discriminated unions provide support for values that can be one of a number of named cases, possibly each with different values and types: t y p e type name = case i d e n t i f i e r 1 [ o f [ f i e l d n a m e 1 : ] type1 [ [ f i e l d n a m e 2 : ] type2... ] case i d e n t i f i e r 2 [ o f [ f i e l d n a m e 3 : ] type3 [ [ f i e l d n a m e 4 : ] type4... ] 41 / 51

Custom data type: Discriminated Unions... Discriminated unions provide support for values that can be one of a number of named cases, possibly each with different values and types: t y p e type name = case i d e n t i f i e r 1 [ o f [ f i e l d n a m e 1 : ] type1 [ [ f i e l d n a m e 2 : ] type2... ] case i d e n t i f i e r 2 [ o f [ f i e l d n a m e 3 : ] type3 [ [ f i e l d n a m e 4 : ] type4... ] Example: t y p e Shape = R e c t a n g l e o f width : f l o a t l e n g t h : f l o a t C i r c l e o f r a d i u s : f l o a t Prism o f width : f l o a t f l o a t h e i g h t : f l o a t 41 / 51

Example: Binary Search Trees! Binary search trees keep their keys in sorted order: elements are inserted/removed from the tree by following the principle of binary search; elements traverse the tree from root to leaf by making decisions on the base of comparison. 42 / 51

Example: Binary Search Trees! Binary search trees keep their keys in sorted order: elements are inserted/removed from the tree by following the principle of binary search; elements traverse the tree from root to leaf by making decisions on the base of comparison. Exercise: 1. develop a data type for BST; 2. implement basic operations on BST... insertion; search; deletion. 42 / 51

Example: Binary Search Trees! Data type: t y p e b s t r e e = EMPTY NODE o f v a l u e : i n t l e f t : b s t r e e r i g h t : b s t r e e 43 / 51

Example: Binary Search Trees! Data type: t y p e b s t r e e = EMPTY NODE o f v a l u e : i n t l e f t : b s t r e e r i g h t : b s t r e e Add a value in the tree: l e t r e c add v t = match t with EMPTY > NODE( v, EMPTY,EMPTY) NODE( v1, l, r ) when v1<v > NODE( v1, l, add v r ) NODE( v1, l, r ) > NODE( v1, add v l, r ) 43 / 51

Example: Binary Search Trees! Search for an element: l e t r e c c o n t a i n s v t = match t with EMPTY > f a l s e NODE( v1,, ) when v1=v > t r u e NODE( v1, l, r ) when v1<v > c o n t a i n s v r NODE( v1, l, r ) > c o n t a i n s v l 44 / 51

Example: Binary Search Trees! Search for an element: l e t r e c c o n t a i n s v t = match t with EMPTY > f a l s e NODE( v1,, ) when v1=v > t r u e NODE( v1, l, r ) when v1<v > c o n t a i n s v r NODE( v1, l, r ) > c o n t a i n s v l Merging trees: l e t r e c merge t1 t2 = match t1, t2 with EMPTY, > t 2,EMPTY > t 1 NODE( v1, l1, r1 ),NODE( v2, l2, r2 ) when v1<v2 > NODE( v1, l1, merge r1 t2 ) NODE( v1, l1, r1 ),NODE( v2, l2, r2 ) > NODE( v2, l2, merge r2 t1 ) 44 / 51

Example: Binary Search Trees! Removing an element: l e t r e c remove v t = match t with EMPTY > EMPTY NODE( v1, l, r ) when v1=v > merge l r NODE( v1, l, r ) when v1<v > NODE( v1, l, remove v r ) NODE( v1, l, r ) > NODE( v1, remove v l, r ) 45 / 51

Exercises... Ex. 4 Implement function size that given a tree t computes the number of elements stored in t. Ex. 5 Implement function height that given a tree t computes its height (an empty BST has height equal to 0). Ex. 6 Implement function balance that given a tree t computes a tree t1 with the same elements its height (an empty BST has height equal to 0). Ex. 7 Implement AVL data structure. 46 / 51

Remarks... The type bstree can only contain integer values. 47 / 51

Remarks... The type bstree can only contain integer values. It could be convenient, like we already observed for lists, define this type as parametrised! 47 / 51

Remarks... The type bstree can only contain integer values. It could be convenient, like we already observed for lists, define this type as parametrised! The exact type of elements in a bstree could be chosen by the programmer! 47 / 51

Remarks... The type bstree can only contain integer values. It could be convenient, like we already observed for lists, define this type as parametrised! The exact type of elements in a bstree could be chosen by the programmer! We can use Generics! 47 / 51

Generics... Generic programming is a style of computer programming in which elements of a program (procedures, functions, data-types,... ) are written in terms of types to-be-specified-later. 48 / 51

Generics... Generic programming is a style of computer programming in which elements of a program (procedures, functions, data-types,... ) are written in terms of types to-be-specified-later. These type parameters are then instantiated when needed for specific types provided as parameters. 48 / 51

Generics... Generic programming is a style of computer programming in which elements of a program (procedures, functions, data-types,... ) are written in terms of types to-be-specified-later. These type parameters are then instantiated when needed for specific types provided as parameters. A generic indicates values, methods, properties, and aggregate types such as classes, records, and discriminated unions can be generic. 48 / 51

Generics... Generic programming is a style of computer programming in which elements of a program (procedures, functions, data-types,... ) are written in terms of types to-be-specified-later. These type parameters are then instantiated when needed for specific types provided as parameters. A generic indicates values, methods, properties, and aggregate types such as classes, records, and discriminated unions can be generic. In F# function values, methods, properties, and aggregate types such as classes, records, and discriminated unions can be generic. 48 / 51

Generics... 49 / 51

Generics... Generic constructs contain at least one type parameter, which is usually supplied by the user of the generic construct. 49 / 51

Generics... Generic constructs contain at least one type parameter, which is usually supplied by the user of the generic construct. Generic functions and types enable you to write code that works with a variety of types without repeating the code for each type: / E x p l i c i t l y g e n e r i c f u n c t i o n. l e t f u n c t i o n name<type parameters > parameter l i s t = f u n c t i o n body // E x p l i c i t l y g e n e r i c t y p e. t y p e type name<type parameters > type d e f i n i t i o n 49 / 51

Generics... Automatic Generation: Type Inference The F# compiler, when it performs type inference on a function, determines whether a given parameter can be generic. 50 / 51

Generics... Automatic Generation: Type Inference The F# compiler, when it performs type inference on a function, determines whether a given parameter can be generic. The compiler examines each parameter and determines whether the function has a dependency on the specific type of that parameter. If it does not, the type is inferred to be generic. 50 / 51

Generics... Automatic Generation: Type Inference The F# compiler, when it performs type inference on a function, determines whether a given parameter can be generic. The compiler examines each parameter and determines whether the function has a dependency on the specific type of that parameter. If it does not, the type is inferred to be generic. Example: l e t max a b = i f a > b then a e l s e b This function has type a > a > a when a comparison. 50 / 51

Generics... Automatic Generation: Type Inference The F# compiler, when it performs type inference on a function, determines whether a given parameter can be generic. The compiler examines each parameter and determines whether the function has a dependency on the specific type of that parameter. If it does not, the type is inferred to be generic. Example: l e t max a b = i f a > b then a e l s e b This function has type a > a > a when a comparison. Above when a comparison is a constraint. 50 / 51

Example... We can change the definition of bstree as follows: t y p e b s t r e e < T when T: comparison > = EMPTY NODE o f v a l u e : T l e f t : T b s t r e e r i g h t : T b s t r e e 51 / 51

Example... We can change the definition of bstree as follows: t y p e b s t r e e < T when T: comparison > = EMPTY NODE o f v a l u e : T l e f t : T b s t r e e r i g h t : T b s t r e e We have not to change the functions add, contains, and remove! 51 / 51