Higher-order operators. Higher-order operators. Scala. Higher-order operators. Java8. numerosi operatori higher-order sulle collezioni
|
|
- Millicent Stone
- 5 years ago
- Views:
Transcription
1 numerosi operatori higher-order sulle collezioni fold left /: fold right :\ filter partition find foreach takewhile dropwhile span (Splits into a prefix/suffix pair according to a predicate) forall exists (z /: List(a,b,c))(op) = op(op(z,a),b),c) def sum(xs:list[int]):int = (0/: xs) (_+_) def product(xs:list[int):int = (1/:xs)(_*_) > val words = List( the, quick, brown, fox ) res: List[java.lang.String] = List(the,quick,brown,fox) String => Int > words map (_.length) res: List[Int] = List(3,5,5,3) > words map (_.tolist) res: List[List[Char]] = List(List(t,h,e),List(q,u,i,c,k), List(b,r,o,w,n),List(f,o,x)) > words flatmap(_.tolist) res: List[Char] = List(t,h,e,q,u,i,c,k,b,r,o,w,n,f,o,x) Scala > map(f:a val words => = B) List( the, quick, brown, fox ) trasforma List[A] in List[B] res: List[java.lang.String] = List(the,quick,brown,fox) String => Int > words map (_.length) res: List[Int] = List(3,5,5,3) > words map (_.tolist) res: List[List[Char]] = List(List(t,h,e),List(q,u,i,c,k), List(b,r,o,w,n),List(f,o,x)) > words flatmap(_.tolist) res: List[Char] = List(t,h,e,q,u,i,c,k,b,r,o,w,n,f,o,x) map(f:a => B) trasforma List[A] in List[B] flatmap(f:a => List[B]) trasforma List[A] in List[B], Java8 in classe Stream<A>: Function<? super A,? extends B> Stream<B> map (Function<A,B> lambdaexpr) Stream<B> flatmap (Function<A,Stream<B>> lambdaexpr) flatmap(f:a => List[B]) trasforma List[A] in List[B] un unica lista che concatena tutti i risultati di f Function<? super A,? extends Stream<? extends B>
2 [1,2,3,4] > List.range(1,5) flatmap ( i => List.range(1,i) map (j => (j,i)) ) res:list[(int,int)]=list((1,2),(1,3),(2,3),(1,4),(2,4),(3,4)) flatmap vs for case class Person(name: String, ismale: Boolean, children: Person*) val lara = Person( Lara,false) val bob = Person( Bob,true) val julie = Person( Julie,false,lara,bob) val persons = List(lara,bob,julie) si ottiene la stessa cosa con for(i <- List.range(1,5); j <- List.range(1,i)) yield (j,i) for { i <- List.range(1,5) j <- List.range(1,i) yield (j,i) persons filter (p =>!p.ismale) flatmap (p => (p.children map (c => (p.name, c.name)))) //oppure for (p <- persons ; if p!p.ismale ; c <- p.children) compilato in yield (p.name, c.name) res:list[(string,string)] = List((Julie,Lara),(Julie,Bob)) for expressions for ( seq ) yield expr for! map,flatmap,filter for (x <- expr1) yield expr2 expr1.map(x => expr2) sequence of generators, definitions and filters with ; between them (or without it if using for{ yield ) for (p<-persons; n=p.name; if (n startswith To )) yield n for (x <- expr1 if expr2) yield expr3 is a for-expression since it returns a value expr1 filter(x => expr2) map(x => expr3) oppure for { p <- persons n = p.name if (n startswith To ) yield n for (x <- expr1; y <- expr2) yield expr3 for (x <- expr1) body expr1 flatmap(x => expr2 map(y => expr3)) is a for-loop since it just performs side-effects expr1 foreach ( x => body )
3 generalizing for for -> map,flatmap,filter the translajon of for-expr. happens before type checking, therefore it is only required that the result of the expansion type checks; there are no typing rules for the for construct! thanks to this translajon for expressions can be applied to any class of data that supports map, flatmap and filter (e.g. lists and arrays) for loops can be applied to any class of data that supports (also) foreach (e.g. lists and arrays) if a (user-defined) datatype defines a subset of these methods, then it sjll supports a subset of all possible for expressions or loops generalizing for abstract class M[A] { def map[b](f: A => B): M[B] def flatmap[b](f: A => M[B]): M[B] def filter(p: A => Boolean): M[A] def foreach(b: A => Unit): Unit unit func<on : A => M[A] return in Haskell, costrusore in Scala binding opera<on : M[A] => (A => M[B]) => M[B] >>= in Haskell, flatmap in Scala then opera<on : M[A] => (A => B) => M[B] >> in Haskell, map in Scala definibile in termini di unit f. e binding op. do-na<on in Haskell corrisponde a for-expressions in Scala together with a constructor or a factory method A => M[A] gives a MONAD (in OOP style) a Monad is a class of types (like a CollecJon is a class of types) OpJon Types e monadi Da API di Option[T]: they represent optional values. Instances of Option are either an instance :Option[String] of scala.some or the object None. val namemaybe = request getparameter "name" namemaybe match { case Some(name) => println(name.trim.touppercase) case None => println("no name value") val name = request getparameter "name" less-idiomatic most idiomatic val upper = name map { _.trim filter { _.length!= 0 map { _.touppercase println(upper getorelse "") OpJon Types e monadi Da API di Option[T]: they represent optional values. Instances of Option are either an instance :Option[String] of scala.some or the object None. val namemaybe = request getparameter "name" namemaybe match { case Some(name) => println(name.trim.touppercase) case None => println("no name value") if None is returned from getparameter, the entire expression results in None. This allows for sophisticated chaining of scala.option values without having to check for the existence of a value. val name = request getparameter "name" less-idiomatic most idiomatic val upper = name map { _.trim filter { _.length!= 0 map { _.touppercase println(upper getorelse "") treat it as a collection or monad and use map,flatmap, filter, or foreach: treat it as a collection or monad and use map,flatmap, filter, or foreach:
4 OpJon Types e monadi val namemaybe = request getparameter "name" most idiomatic val upper = namemaybe map { _.trim filter { _.length!=0 map { _.touppercase println(upper getorelse "") this is equivalent to val upper = for { name <- request getparameter "name" trimmed <- Some(name.trim) upper <- Some(trimmed.toUpperCase) if trimmed.length!= 0 yield upper println(upper getorelse " ) if None is returned from getparameter, the entire expression results in None. This allows for sophisticated chaining of scala.option values without having to check for the existence of a value. OpJon Types e monadi nella classe Option[A] sono definij final def filter(p:a => Boolean) : Option[A] returns this OpJon if it is nonempty and applying the predicate p to this OpJon s value returns true. Otherwise, return None final def map[b](f:a => B):Option[B] returns a Some containing the result of applying f to this OpJon s value if this OpJon is nonempty. Otherwise return None final def flatmap[b](f:a => Option[B]):Option[B] returns the result of applying f to this OpJon s value if this OpJon is nonempty. Returns None if this Op2on is empty. Slightly different from map in that f is expected to return an OpJon (which could be None) Try[T] Try[T] val x = obj.m1() val y = obj.m2(x) def m1():t =... def m2(x:t):s=... val x = obj.m1() val y = obj.m2(x) def m1():t =... def m2(x:t):s=... semplice ma m1 e m2 possono sollevare eccezioni def m1():try[t] =... def m2(x:t):try[s]=... Try[T] e il tipo di una computazione che può fallire Espone la possibilità di fallire a livello dei tipi abstract class Try[+T] case class Success[T](x:T) extends Try[T] case class Failure(ex:Exception) extends Try[Nothing] serious system errors are thrown as usual def m1():try[t] =... def m2(x:t):try[s]=... val x:try[t] = obj.m1() val y = obj.m2(x) NON COMPILA val x:try[t]= obj.m1() val y:try[s]= x flatmap ( _ => obj.m2(_)) Try[T] e una monade: ha definij i metodi map e flatmap
5 val x = obj.m1() val y = obj.m2(x) Try[T] codice orientato alla programmazione Fault Tolerant def m1():t =... def m2(x:t):s=... def m1():try[t] =... def m2(x:t):try[s]=... :Future[T] :T val x = future { someexpensivecomputation() val y = future { someotherexpensivecomputation() val z = for (a <- x; b <- y) yield a*b for (c <- z) println("result: " + c) println("meanwhile, the main thread goes on!") val x:try[t] = obj.m1() val y = obj.m2(x) NON COMPILA someexpensivecomp a*b val y:try[s]= for ( x <- obj.m1() y <- obj.m2(x) ) yield y NOTA: se m1 o m2 ritorna Failure, allora y ha valore Failure senza bisogno di fare il check a mano someotherexpensivecomp print( Meanwhile... ) print( Result +c) preparazione di cappuccino macinare i grani di caffè bollire l acqua fare il caffè fare la schiuma di latte preparazione di cappuccino macinare i grani di caffè bollire l acqua fare il caffè fare la schiuma di latte combinare caffè e schiuma di latte combinare caffè e schiuma di latte
6 type GraniCaffe = String type PolvereCaffe = String type Latte = String type Schiuma = String type Espresso = String type Cappuccino = String case class Acqua(temp:Int) def macina(grani:granicaffe):try[polverecaffe] =... def bollire(acqua:acqua): Acqua = def preparacappuccseqentially(): Try[Cappuccino] = for( m <- macina( arabica ) a <- bollire(acqua(25)) s <- faischiuma( latte ) ) yield mescola(e,s) Tipo di computazione che può fallire for-expr. che gestisce il caso Failure def macina(grani:granicaffe): Try[PolvereCaffe] = { println( inizia a macinare ) if(grani== orzo ) throw MacinaException( scherziamo? ) println( finito di macinare ) polvere di +grani def bollire(acqua:acqua): Acqua = { println( scalda acqua ) println( bolle! ) acqua.copy(temp = 85) def macina(grani:granicaffe): Future[PolvereCaffe] = Future { println( inizia a macinare ) if(grani== orzo ) throw MacinaException( scherziamo? ) println( finito di macinare ) polvere di +grani def bollire(acqua:acqua): Future[Acqua] = Future { println( scalda acqua ) println( bolle! ) acqua.copy(temp = 85) def preparacappucc(): Future[Cappuccino] = val macina = macina( arabica ) val acquacalda = bollire(acqua(25)) val schiuma = faischiuma( latte ) restituiscono subito un Future, che sarà completato asincronamente def preparacappuccseqentially(): Try[Cappuccino] = for( m <- macina( arabica ) a <- bollire(acqua(25)) s <- faischiuma( latte ) ) yield mescola(e,s) def preparacappucc(): Future[Cappuccino] = val macina = macina( arabica ) val acquacalda = bollire(acqua(25)) val schiuma = faischiuma( latte ) for( m <- macina a <- acquacalda s <- schiuma ) yield mescola(e,s) for( m <- macina a <- acquacalda s <- schiuma ) yield mescola(e,s)
List are immutable Lists have recursive structure Lists are homogeneous
WORKING WITH LISTS val fruit = List("apples", "oranges", "pears") val nums: List[Int] = List(1, 2, 3, 4) val diag3 = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) val empty = List() List are immutable
More informationProgramming Principles
Programming Principles Final Exam Wednesday, December 18th 2013 First Name: Last Name: Your points are precious, don t let them go to waste! Your Name Work that can t be attributed to you is lost: write
More informationExercise 1: Graph coloring (10 points)
Exercise 1: Graph coloring (10 points) Graph coloring is the problem of assigning colors to vertices in a non-directed graph, so that no two adjacent nodes have the same color. In other words, if two vertices
More informationFunctional Programming
Functional Programming Final Exam Friday, December 18 2015 First Name: Last Name: Your points are precious, don t let them go to waste! Your Name Work that can t be attributed to you is lost: write your
More informationOverview. Elements of Programming Languages. Advanced constructs. Motivating inner class example
Overview Elements of Programming Languages Lecture 11: Object-oriented functional programming James Cheney University of Edinburgh October 30, 2017 We ve now covered: basics of functional programming (with
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 6a Andrew Tolmach Portland State University 1994-2016 Functional Programming An alternative paradigm to imperative programming First-class functions Emphasis
More informationStrings are not collections, but they behave like them in almost every way. For example,
Functional Programming Style Drew McDermott drew.mcdermott@yale.edu 2015-09-30 & 10-02 Revised 2015-10-15, by addition of paragraph on type ascription in case clauses at the end of the section Variable
More informationComp 311 Functional Programming. Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sagnak Tasirlar, Two Sigma Investments
Comp 311 Functional Programming Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sagnak Tasirlar, Two Sigma Investments How to Decide Between Structural and Generative Recursion
More informationMonadologie. professional help for type anxiety. Christopher League 12 July 2010
Monadologie professional help for type anxiety Christopher League 12 July 2010 Monadologie github.com/league/scala-type-anxiety @chrisleague league@contrapunctus.net 1996 Principles of Programming Languages
More informationCollections and Combinatorial Search
Streams Collections and Combinatorial Search We ve seen a number of immutable collections that provide powerful operations, in particular for combinatorial search. For instance, to find the second prime
More informationPractically Functional. Daniel Spiewak
Practically Functional Daniel Spiewak whoami Author of Scala for Java Refugees and other articles on Scala and FP Former editor Javalobby / EclipseZone Engaged in academic research involving Scala DSLs
More informationLife in a Post-Functional World
Life in a Post-Functional World Definitions Functional Programming Definitions Functional Programming Programming with functions! Definitions Functional Programming Programming with functions! Functions
More informationCPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia
CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple
More informationProgrammi di utilità
Programmi di utilità La classe SystemData per il calcolo dei tempi e della occupazione di memoria Per calcolare i tempi e la occupazione di memoria è necessario interagire con il sistema operativo, questo
More informationScala The learning curve. Aleksandar Prokopec
Scala The learning curve Aleksandar Prokopec Sometime back in 2008 beans Sometime back in 2008 List beans = Sometime back in 2008 List
More informationLinked lists and the List class
Linked lists and the List class Cheong 1 Linked lists So far, the only container object we used was the array. An array is a single object that contains references to other objects, possibly many of them.
More informationUsing Scala in CS241
Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes
More informationArne Brüsch Philipp Wille. Pattern Matching Syntax
Scala Enthusiasts BS Arne Brüsch Philipp Wille Pattern Matching Syntax Scala Modular programming language Some used to call it objectfunctional 2 Scala Modular programming language Some used to call it
More informationDownload the forcomp.zip handout archive file and extract it somewhere on your machine.
Anagrams: Instructions When you're ready to submit your solution, go to the assignments list. Download the forcomp.zip handout archive file and extract it somewhere on your machine. In this assignment,
More informationCSE 130, Fall 2006: Final Examination
CSE 130, Fall 2006: Final Examination Name: ID: Instructions, etc. 1. Write your answers in the space provided. 2. Wherever it says explain, write no more than three lines as explanation. The rest will
More informationCATEGORIES AND COMPUTATION BRIEF MONAD EXAMPLE. Andrew R. Plummer. Department of Linguistics The Ohio State University.
BRIEF MONAD EXAMPLE Andrew R. Plummer Department of Linguistics The Ohio State University 28 Oct, 2009 OUTLINE 1 CATEGORIES AND COMPUTATION IO PROBLEM AS MOTIVATION Suppose we have a relation R between
More informationCIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL
CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,
More informationCSE341 Section 3. Standard-Library Docs, First-Class Functions, & More
CSE341 Section 3 Standard-Library Docs, First-Class Functions, & More Adapted from slides by Daniel Snitkovskiy, Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman Agenda 1. SML Docs Standard
More informationCompile-Time Code Generation for Embedded Data-Intensive Query Languages
Compile-Time Code Generation for Embedded Data-Intensive Query Languages Leonidas Fegaras University of Texas at Arlington http://lambda.uta.edu/ Outline Emerging DISC (Data-Intensive Scalable Computing)
More informationCSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures
CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated
More informationLazy Scheme. Version 4.0. June 11, 2008
Lazy Scheme Version 4.0 June 11, 2008 #lang lazy Lazy Scheme is available as both a language level and a module that can be used to write lazy code. To write lazy code, simply use lazy as your module s
More informationEECS 700 Functional Programming
EECS 700 Functional Programming Dr. Andy Gill University of Kansas February 16, 2010 1 / 41 Parsing A parser is a program that analyses a piece of text to determine its syntactic structure. The expression
More informationOverview. Elements of Programming Languages. Another example. Consider the humble identity function
Overview Elements of Programming Languages Lecture 8: Polymorphism and type inference James Cheney University of Edinburgh October 21, 2016 This week and next week, we will cover di erent forms of abstraction
More informationCode Listings. Inheritance APPENDIX A. Subtype Inheritance in Java
APPENDIX A For the full source, see https://github.com/tobyweston/learn-scala-java-devs. The following is a selection of examples from the text, expanded to provide fuller context for your reference. Inheritance
More informationLazy Evaluation in Scala
Lazy Evaluation Lazy Evaluation The proposed implementation suffers from a serious potential performance problem: If tail is called several times, the corresponding stream will be recomputed each time.
More informationCSCE 314 Programming Languages
CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as
More informationBig Data Analytics with Apache Spark. Nastaran Fatemi
Big Data Analytics with Apache Spark Nastaran Fatemi Apache Spark Throughout this part of the course we will use the Apache Spark framework for distributed data-parallel programming. Spark implements a
More informationCS 2340 Objects and Design - Scala
CS 2340 Objects and Design - Scala Objects and Operators Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 2340 Objects and Design - Scala Objects and Operators 1 / 13 Classes
More informationShell CSCE 314 TAMU. Higher Order Functions
1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.
More informationSurfing Ada for ESP Part 2
Surfing Ada for ESP Part 2 C. Montangero Dipartimento d Informatica Corso di ESperienze di Programmazione a.a. 2012/13 1 Table of contents 2 CHAPTER 9: Packages Packages allow the programmer to define
More informationCS Programming Languages: Scala
CS 3101-2 - Programming Languages: Scala Lecture 3: Fun with Functions Daniel Bauer (bauer@cs.columbia.edu) October 29, 2014 Daniel Bauer CS3101-2 Scala - 03 - Fun with Functions 1/37 Contents 1 Defining
More informationCompSci 220. Programming Methodology 12: Functional Data Structures
CompSci 220 Programming Methodology 12: Functional Data Structures A Polymorphic Higher- Order Function def findfirst[a](as: Array[A], p: A => Boolean): Int = { def loop(n: Int): Int = if (n >= as.length)
More informationan overview Alceste Scalas Programming languages reading group
an overview Alceste Scalas Programming languages reading group 31 October 2017 Scala: what s the hype about? Object oriented and functional programming language Runs on the JVM... interoperability with
More informationTopic 13: Packages and Imports
Topic 13: Packages and Imports Exercise Jesper Pedersen Notander Department of Computer Science Lund University Faculty of Engineering Learning Scala Seminar 3 Instructions Code Solution Instructions Study
More informationDraft Rosen Multicast. Massimiliano Sbaraglia
Draft Rosen Multicast Massimiliano Sbaraglia MDT Draft Rosen layer 3 Multicast VPN Consiste in una VPN multicast con PIM (Protocol Indipendent Multicast) configurato sia all interno della VPN stessa che
More informationSpark Streaming. Guido Salvaneschi
Spark Streaming Guido Salvaneschi 1 Spark Streaming Framework for large scale stream processing Scales to 100s of nodes Can achieve second scale latencies Integrates with Spark s batch and interactive
More informationAutomatic Creation of Define.xml for ADaM
Automatic Creation of Define.xml for ADaM Alessia Sacco, Statistical Programmer www.valos.it info@valos.it 1 Indice Define.xml Pinnacle 21 Community Valos ADaM Metadata 2 Define.xml Cos è: Case Report
More informationINTRODUCTION. SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova
SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2014 2015 rcardin@math.unipd.it INTRODUCTION Object/functional
More informationScala : an LLVM-targeted Scala compiler
Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................
More informationThe SCAlable LAnguage
The SCAlable LAnguage The Scala Language: Object Oriented Functional Programming Gabor Szokoli Overview Introduction Everything is an Object Inheritance and mixins For comprehensions Generic Types: Covariance,
More informationHaskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder
Outline 1 2 3 4 What is Haskell? Haskell is a functional programming language. Characteristics functional non-strict ( lazy ) pure (no side effects*) strongly statically typed available compiled and interpreted
More informationJVM ByteCode Interpreter
JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first
More informationStandard prelude. Appendix A. A.1 Classes
Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from
More informationLaboratorio di Sistemi Software Design Patterns 2
TITLE Laboratorio di Sistemi Software Design Patterns 2 Luca Padovani (A-L) Riccardo Solmi (M-Z) 1 Indice degli argomenti Tipi di Design Patterns Creazionali, strutturali, comportamentali Design Patterns
More informationCS 457/557: Functional Languages
CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is
More information// Body of shortestlists starts here y flatmap { case Nil => Nil case x :: xs => findshortest(list(x), xs)
8 Shortest-strings Problem: Partial-Solution Dump Drew McDermott drew.mcdermott@yale.edu Lecture notes for 2016-09-19, revised 20016-09-25 Here is the state of play in solving the little puzzle about finding
More informationComputation Abstraction Going beyond programming language glue, or what we've missed from FP for so long in mainstream
Computation Abstraction Going beyond programming language glue, or what we've missed from FP for so long in mainstream googlewave.com!w+pgcakhgia Sadek Drobi Consultant (j2ee,.net) Programming Languages
More informationKafka Streams: Hands-on Session A.A. 2017/18
Università degli Studi di Roma Tor Vergata Dipartimento di Ingegneria Civile e Ingegneria Informatica Kafka Streams: Hands-on Session A.A. 2017/18 Matteo Nardelli Laurea Magistrale in Ingegneria Informatica
More informationGADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]
GADTs Advanced functional programming - Lecture 7 Wouter Swierstra and Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree
More informationYou ve encountered other ways of signalling errors. For example, if you lookup an unbound key in a hashtable, Java (and Scala) produce nulls:
Lecture 5 1 Required Reading Read Chapters 16 and 17 of Programming in Scala. 2 Partial Functions and Signalling Errors Many functions are not defined on all inputs. For example, if you re reading input
More informationGADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]
GADTs AFP Summer School Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces: 3 A datatype data
More informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
More informationElements of Programming Languages Assignment 1: Introduction to Scala September 27, 2017
Elements of Programming Languages Assignment 1: Introduction to Scala September 27, 2017 This laboratory session is intended to introduce you to the basic features of Scala, focusing primarily on the pure,
More informationIntroduction to Spark
Introduction to Spark Outlines A brief history of Spark Programming with RDDs Transformations Actions A brief history Limitations of MapReduce MapReduce use cases showed two major limitations: Difficulty
More informationProgramming Languages 3. Definition and Proof by Induction
Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.
More informationO futuro chegou: Programação concorrente com futures LEONARDO BORGES SENIOR CLOJURE
O futuro chegou: Programação concorrente com futures LEONARDO BORGES SENIOR CLOJURE ENGINEER @LEONARDO_BORGES SOBRE Um pouco sobre mim Senior Clojure Engineer na Atlassian, Sydney Fundador do Grupo de
More informationCSCE 314 Programming Languages. Functional Parsers
CSCE 314 Programming Languages Functional Parsers Dr. Hyunyoung Lee 1 What is a Parser? A parser is a program that takes a text (set of tokens) and determines its syntactic structure. String or [Token]
More informationSearching and Strings. IST 256 Application Programming for Information Systems
Searching and Strings IST 256 Application Programming for Information Systems Searching for Strings In an array, we do a simple linear search for an item by going through the array in order from the first
More informationCSCE 314 Programming Languages. Monadic Parsing
CSCE 314 Programming Languages Monadic Parsing Dr. Hyunyoung Lee 1 What is a Parser? A parser is a program that takes a string of characters (or a set of tokens) as input and determines its syntactic structure.
More informationProgramming Systems in Artificial Intelligence Functional Programming
Click to add Text Programming Systems in Artificial Intelligence Functional Programming Siegfried Nijssen 8/03/16 Discover thediscover world at the Leiden world University at Leiden University Overview
More informationVHDL Packages. I Packages incapsulano elementi che possono essere condivisi tra più entity Un package consiste di due parti:
1 VHDL Packages I Packages incapsulano elementi che possono essere condivisi tra più entity Un package consiste di due parti: Declaration Dichiarazione di tutti gli elementi contenuti nel package Body
More informationPrograms as Data. The Scala language
Programs as Data The Scala language Peter Sestoft 2011-11-14 1 Agenda Kursusevaluering slutter i dag! Object-oriented programming in Scala Classes Singletons (object) Traits Compiling and running Scala
More informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
More informationSerie Sistema scorrevoleve regolabile o fisso per armadi con ante interne. Adjustable or fixed sliding system for wardrobes with internal doors
Serie Sistema scorrevoleve regolabile o fisso per armadi con ante interne Adjustable or fixed sliding system for wardrobes with internal doors , 1 1 1, 4 1 1 11, 4 4 4 4 4 4 Posizione binari Rails position
More informationIntroduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples
Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the
More informationINTRODUCTION TO SCHEME
INTRODUCTION TO SCHEME PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2019 Dalhousie University 1/110 SCHEME: A FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be passed as
More informationScala Concurrency and Parallel Collections
Scala Concurrency and Parallel Collections Concurrent Programming Keijo Heljanko Department of Computer Science University School of Science November 23rd, 2016 Slides by Keijo Heljanko Scala Scala Originally
More informationData types à la carte. Wouter Swierstra Dutch HUG 25/8/10
Data types à la carte Wouter Swierstra Dutch HUG 25/8/10 Expressions data Expr where Add :: Expr -> Expr -> Expr Val :: Int -> Expr eval :: Expr -> Int eval (Val x) = x eval (Add l r) = eval l + eval r
More informationOverview. Elements of Programming Languages. Evaluation order. Evaluation order
Overview Elements of Programming Languages Lecture 15: Evaluation strategies and laziness James Cheney University of Edinburgh November 18, 216 Final few lectures: cross-cutting language design issues
More informationImplementazione Alberi Binari. mediante. Linked Structure ( 7.3.4)
Implementazione Alberi Binari mediante Linked Structure ( 7.3.4) 1 Implementazione di AlberoBinario Vedi testo pag. 290 B A D C E 2 1 Implementazione di AlberoBinario Position Tree extends BTPosition extends
More information15 Multiple Inheritance and Traits
Object-Oriented Design Lecture 15 CS 3500 Fall 2010 (Pucella) Tuesday, Nov 9, 2010 15 Multiple Inheritance and Traits Recall our code for MList from last time. We defined MList to be a subtype of List,
More informationImperative Programming 2: Traits
Imperative Programming 2: Traits Hongseok Yang University of Oxford Experience with traits so far In IP1, you have used traits as interfaces, in order to specify available methods and fields. trait IntQueue
More informationWhat the optimizer does to your code
1 / 12 Miguel Garcia http://lamp.epfl.ch/~magarcia LAMP, EPFL 2012-04-18 2 / 12 Outline Things the optimizer is good at Example Pros and Cons Early inlining Parallelizing an optimization phase Further
More informationAnnouncements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy
Announcements CSCI 334: Principles of Programming Languages Lecture 16: Intro to Scala HW7 sent out as promised. See course webpage. Instructor: Dan Barowy Announcements No class on Tuesday, April 17.
More informationDatatype declarations
Datatype declarations datatype suit = HEARTS DIAMONDS CLUBS SPADES datatype a list = nil (* copy me NOT! *) op :: of a * a list datatype a heap = EHEAP HEAP of a * a heap * a heap type suit val HEARTS
More informationChapter 15 Functional Programming Languages
Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.
More informationGeneratore di parità. LIBRARY ieee; USE ieee.std_logic_1164.all ; ENTITY xor2 IS PORT( A, B : in std_logic ; Y : out std_logic ) ; END xor2 ;
LIBRARY ieee; USE ieee.std_logic_1164.all ; ENTITY xor2 IS PORT( A, B : in std_logic ; Y : out std_logic ) ; END xor2 ; ARCHITECTURE arch1 OF Xor2 IS BEGIN Y
More informationSoftware Engineering Design & Construction
Winter Semester 17/18 Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt A Critical View on Inheritance 2 A Critical View On Inheritance
More informationJava 9 New features 8/11/2017 Iason Dimitrios Rodis
Java 9 New features 8/11/2017 Iason Dimitrios Rodis 2 Java 9 - New features Release date: September 21st 2017 Features: Java 9 REPL (JShell) Factory Methods for Immutable List, Set, Map and Map.Entry Private
More informationPrinciples of Programming Languages
Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp-16/ Prof. Andrea Corradini Department of Computer Science, Pisa Control Flow Iterators Recursion Con>nua>ons Lesson 25! 1 Iterators
More informationSAFE DESIGNED IN ITALY CASSEFORTI PER HOTEL HOTEL SAFES
DESIGNED IN ITALY CASSEFORTI PER HOTEL HOTEL S : I MODELLI : MODELS TOP OPEN DRAWER Innovativa tastiera touch e display led integrato nella porta New touch keypad and stealthy LED display L apertura dall
More informationGADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences
GADTs Advanced functional programming - Lecture 7 Wouter Swierstra 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces:
More informationCSCE 314 Programming Languages. Monadic Parsing
CSCE 314 Programming Languages Monadic Parsing Dr. Hyunyoung Lee 1 What is a Parser? A parser is a program that takes a string of characters (or a set of tokens) as input and determines its syntactic structure.
More informationRaccolta semiseria di errori comuni e stili di programmazione da evitare.
Lo Stupidario di Fondamenti 2 Raccolta semiseria di errori comuni e stili di programmazione da evitare. Daniele Paolo Scarpazza Politecnico di Milano Ultimo aggiornamento: 2004-03-03 Lo Stupidario di Fondamenti
More informationLanguage Reference Manual
Espresso Language Reference Manual 10.06.2016 Rohit Gunurath, rg2997 Somdeep Dey, sd2988 Jianfeng Qian, jq2252 Oliver Willens, oyw2103 1 Table of Contents Table of Contents 1 Overview 3 Types 4 Primitive
More informationChapter 5 Data Link Layer
Chapter 5 Data Link Layer Reti di Elaboratori Corso di Laurea in Informatica Università degli Studi di Roma La Sapienza Canale A-L Prof.ssa Chiara Petrioli Parte di queste slide sono state prese dal materiale
More informationCITS3211 FUNCTIONAL PROGRAMMING. 6. Folding operators
CITS3211 FUNCTIONAL PROGRAMMING 6. Folding operators Summary: This lecture discusses an important group of higher order functions known as the folding operators. Almost any recursive function over lists
More informationClassical Themes of Computer Science
Functional Programming (Part 1/2) Bernhard K. Aichernig Institute for Software Technology Graz University of Technology Austria Winter Term 2017/18 Version: November 22, 2017 1/49 Agenda I Functional Programming?
More informationPrograms as Values Pure Functional Database Access in Scala
Programs as Values Pure Functional Database Access in Scala Rob Norris Gemini Observatory Programs as Values Pure Functional Database Access in Scala Rob Norris Gemini Observatory What's this about? This
More informationPLanCompS. Peter D Mosses Swansea University. SSLF12: Summer School on Language Frameworks Sinaia, Romania, July 2012
PLanCompS Peter D Mosses Swansea University SSLF12: Summer School on Language Frameworks Sinaia, Romania, July 2012 1 PLANCOMPS Programming Languages (incl. DSLs) C# Java translation Components and their
More informationChapter 9 Formattazione Input/Output
1 Chapter 9 Formattazione Input/Output 2 Flussi 9.2 Flussi Sequenze di caratteri organizzate in linee Ogni linea consiste di zero o più caratteri e finisce con il carattere newline Lo standard ANSI C deve
More informationOutline. Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists
Arrays and Lists Outline Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists Collections We've seen tuples to store multiple objects together, but the tuple
More informationHarvard School of Engineering and Applied Sciences CS 152: Programming Languages
Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Lecture 18 Thursday, March 29, 2018 In abstract algebra, algebraic structures are defined by a set of elements and operations
More informationMicroservices. Webservices with Scala (II) Microservices
Microservices Webservices with Scala (II) Microservices 2018 1 Content Deep Dive into Play2 1. Database Access with Slick 2. Database Migration with Flyway 3. akka 3.1. overview 3.2. akka-http (the http
More informationCSE341 Spring 2017, Final Examination June 8, 2017
CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please
More information