SlideShare a Scribd company logo
1 of 21
Download to read offline
CSE341: Programming Languages
               Lecture 4
Records (“each of”), Datatypes (“one of”),
           Case Expressions
               Dan Grossman
                 Fall 2011
Review

• Done: functions, tuples, lists, local bindings, options

• Done: syntax vs. semantics, environments, mutation-free

• Today: Focus on compound types
   – New feature: records
      • New concept: syntactic sugar (tuples are records)
   – New features: datatypes, constructors, case expressions




Fall 2011               CSE341: Programming Languages          2
How to build bigger types

• Already know:
   – Have various base types like int bool unit char
      – Ways to build (nested) compound types: tuples, lists, options

• Today: more ways to build compound types

• First: 3 most important type building blocks in any language
   – “Each of”: A t value contains values of each of t1 t2 … tn
   – “One of”: A t value contains values of one of t1 t2 … tn
   – “Self reference”: A t value can refer to other t values
      Remarkable: A lot of data can be described with just these
      building blocks

      Note: These are not the common names for these concepts
Fall 2011               CSE341: Programming Languages               3
Examples

• Tuples build each-of types
   – int * bool contains an int and a bool

• Options build one-of types
   – int option contains an int or it contains no data

• Lists use all three building blocks
   – int list contains an int and another int list or it
      contains no data

• And of course we can nest compound types
   – ((int * int) option) * (int list list)) option


Fall 2011            CSE341: Programming Languages         4
Rest of today

• Another way to build each-of types in ML
   – Records: have named fields
   – Connection to tuples and idea of syntactic sugar

• A way to build and use our own one-of types in ML
   – For example, a type that contains and int or a string
      – Will lead to pattern-matching (more next lecture), one of
        ML’s coolest and strangest-to-Java-programmers features
      – How OOP does one-of types discussed later in course




Fall 2011               CSE341: Programming Languages               5
Records

Record values have fields (any name) holding values
                 {f1 = v1, …, fn = vn}
Record types have fields (and name) holding types
                 {f1 : t1, …, fn : tn}

The order of fields in a record value or type never matters
   – REPL alphabetizes fields just for consistency

Building records:
                    {f1 = e1, …, fn = en}
Accessing components:
                     #myfieldname e

(Evaluation rules and type-checking as expected)
Fall 2011              CSE341: Programming Languages          6
Example
            {name = “Amelia”, id = 41123 - 12}
Evaluates to
               {id = 41111, name = “Amelia”}
And has type
                 {id : int, name : string}

If some expression such as a variable x has this type, then get
fields with:       #id x        #name x

Note we didn’t have to declare any record types
   – The same program could also make a
       {id=true,ego=false} of type {id:bool,ego:bool}

Fall 2011              CSE341: Programming Languages              7
By name vs. by position

• Little difference between (4,7,9) and {f=4,g=7,h=9}
      – Tuples a little shorter
      – Records a little easier to remember “what is where”
      – Generally a matter of taste, but for many (6? 8? 12?) fields, a
        record is usually a better choice

• A common decision for a construct’s syntax is whether to refer
  to things by position (as in tuples) or by some (field) name (as
  with records)
   – A common hybrid is like with Java method arguments (and
      ML functions as used so far):
        • Caller uses position
        • Callee uses variables
        • Could totally do it differently; some languages have
Fall 2011                CSE341: Programming Languages                8
The truth about tuples

Last week we gave tuples syntax, type-checking rules, and
evaluation rules

But we could have done this instead:
    – Tuple syntax is just a different way to write certain records
    – (e1,…,en) is another way of writing {1=e1,…,n=en}
    – t1*…*tn is another way of writing {1:t1,…,n:tn}
      – In other words, records with field names 1, 2, …

In fact, this is how ML actually defines tuples
     – Other than special syntax in programs and printing, they
        don’t exist
     – You really can write {1=4,2=7,3=9}, but it’s bad style
Fall 2011               CSE341: Programming Languages                 9
Syntactic sugar

                “Tuples are just syntactic sugar for
               records with fields named 1, 2, … n”

• Syntactic: Can describe the semantics entirely by the
  corresponding record syntax

• Sugar: They make the language sweeter 

Will see many more examples of syntactic sugar
     – They simplify understanding the language
     – They simplify implementing the language
     Why? Because there are fewer semantics to worry about even
     though we have the syntactic convenience of tuples
Fall 2011             CSE341: Programming Languages           10
Datatype bindings
A “strange” (?) and totally awesome (!) way to make one-of types:
    – A datatype binding

            datatype mytype = TwoInts of int * int
                            | Str of string
                            | Pizza

• Adds a new type mytype to the environment
• Adds constructors to the environment: TwoInts, Str, and Pizza
• A constructor is (among other things), a function that makes
  values of the new type (or is a value of the new type):
   – TwoInts : int * int -> mytype
   – Str : string -> mytype
   – Pizza : mytype

Fall 2011               CSE341: Programming Languages               11
The values we make
            datatype mytype = TwoInts of int * int
                            | Str of string
                            | Pizza

• Any value of type mytype is made from one of the constructors
• The value contains:
  − A “tag” for “which constructor” (e.g., TwoInts)
  − The corresponding data (e.g., (7,9))
− Examples:
  − TwoInts(3+4,5+4) evaluates to TwoInts(7,9)
  − Str(if true then “hi” else “bye”) evaluates to
     Str(“hi”)
  − Pizza is a value


Fall 2011               CSE341: Programming Languages        12
Using them
So we know how to build datatype values; need to access them

There are two aspects to accessing a datatype value
1. Check what variant it is (what constructor made it)
2. Extract the data (if that variant has any)

Notice how our other one-of types used functions for this:
• null and iSome check variants
• hd, tl, and valOf extract data (raise exception on wrong variant)

ML could have done the same for datatype bindings
   – For example, functions like “isStr” and “getStrData”
   – Instead it did something better
Fall 2011              CSE341: Programming Languages           13
Case
ML combines the two aspects of accessing a one-of value with a
case expression and pattern-matching
   – Pattern-matching much more general/powerful (lecture 5)

Example:
            fun f x = (* f has type mytype -> int *)
                case x of
                    Pizza => 3
                  | TwoInts(i1,i2) => i1+i2
                  | Str s => String.size s
•   A multi-branch conditional to pick branch based on variant
•   Extracts data and binds to variables local to that branch
•   Type-checking: all branches must have same type
•   Evaluation: evaluate between case … of and right branch
Fall 2011               CSE341: Programming Languages            14
Patterns
In general the syntax is:
                        case e0       of
                             p1       => e1
                           | p2       => e2
                             …
                           | pn       => en

For today, each pattern is a constructor name followed by the right
number of variables (i.e., C or C x or C(x,y) or …)
      – Syntactically most patterns (all today) look like expressions
      – But patterns are not expressions
         • We do not evaluate them
         • We see if the result of e0 matches them


Fall 2011                CSE341: Programming Languages                  15
Why this way is better

0. You can use pattern-matching to write your own testing and
data-extractions functions if you must
    – But don’t do that on your homework


1. You can’t forget a case (inexhaustive pattern-match a warning)
2. You can’t duplicate a case (a type-checking error)
3. You won’t forget to test the variant correctly and get an
   exception (like hd [])
4. Pattern-matching can be generalized and made more powerful,
   leading to elegant and concise code



Fall 2011              CSE341: Programming Languages            16
Useful examples

Let’s fix the fact that our only example datatype so far was silly…

• Enumerations, including carrying other data

   datatype suit = Club | Diamond | Heart | Spade
   datatype card_value = Jack | Queen | King
                       | Ace | Num of int

• Alternate ways of representing data about things (or people )

   datatype id = StudentNum of int
               | Name of string
                         * (string option)
                         * string

Fall 2011              CSE341: Programming Languages                  17
Don’t do this

Unfortunately, bad training and languages that make one-of types
inconvenient lead to common bad style where each-of types are
used where one-of types are the right tool
        (* use the studen_num and ignore other
          fields unless the student_num is ~1 *)
        { student_num : int,
          first       : string,
          middle      : string option,
          last        : string }


• Approach gives up all the benefits of the language enforcing
  every value is one variant, you don’t forget branches, etc.

• And it makes it less clear what you are doing
Fall 2011             CSE341: Programming Languages                18
That said…

But if instead, the point is that every “person” in your program has a
name and maybe a student number, then each-of is the way to go:


            { student_num       :   int option,
              first             :   string,
              middle            :   string option,
              last              :   string }




Fall 2011              CSE341: Programming Languages                19
Expression Trees
A more exciting (?) example of a datatype, using self-reference
            datatype exp =   Constant         of   int
                         |   Negate           of   exp
                         |   Add              of   exp * exp
                         |   Multiply         of   exp * exp

An expression in ML of type exp:
        Add (Constant (10+9), Negate (Constant 4))

How to picture the resulting value in your head:
                              Add

                   Constant          Negate

                       19          Constant

                                          4
Fall 2011               CSE341: Programming Languages             20
Recursion

Not surprising:
     Functions over recursive datatypes are usually recursive

 fun eval e =
    case e of
         Constant i                =>   i
       | Negate e2                 =>   ~ (eval e2)
       | Add(e1,e2)                =>   (eval e1) + (eval e2)
       | Multiply(e1,e2)           =>   (eval e1) * (eval e2)




Fall 2011             CSE341: Programming Languages             21

More Related Content

What's hot (20)

Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Presentation1
Presentation1Presentation1
Presentation1
 
Language for specifying lexical Analyzer
Language for specifying lexical AnalyzerLanguage for specifying lexical Analyzer
Language for specifying lexical Analyzer
 
Compier Design_Unit I_SRM.ppt
Compier Design_Unit I_SRM.pptCompier Design_Unit I_SRM.ppt
Compier Design_Unit I_SRM.ppt
 
LISP: Input And Output
LISP: Input And OutputLISP: Input And Output
LISP: Input And Output
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Lecture 02 lexical analysis
Lecture 02 lexical analysisLecture 02 lexical analysis
Lecture 02 lexical analysis
 
A simple approach of lexical analyzers
A simple approach of lexical analyzersA simple approach of lexical analyzers
A simple approach of lexical analyzers
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
Lexical Analyzer Implementation
Lexical Analyzer ImplementationLexical Analyzer Implementation
Lexical Analyzer Implementation
 
LISP: Data types in lisp
LISP: Data types in lispLISP: Data types in lisp
LISP: Data types in lisp
 
Elements of functional programming
Elements of functional programmingElements of functional programming
Elements of functional programming
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Lecture4 lexical analysis2
Lecture4 lexical analysis2Lecture4 lexical analysis2
Lecture4 lexical analysis2
 
Scheme Programming Language
Scheme Programming LanguageScheme Programming Language
Scheme Programming Language
 
Compiler lec 8
Compiler lec 8Compiler lec 8
Compiler lec 8
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 

Viewers also liked

Presenting for Results brochure
Presenting for Results brochurePresenting for Results brochure
Presenting for Results brochuresimswyeth
 
九五聯盟 信用卡定期定額扣款授權書
九五聯盟 信用卡定期定額扣款授權書九五聯盟 信用卡定期定額扣款授權書
九五聯盟 信用卡定期定額扣款授權書顥中 王
 
O estado da educacao num estado intervencionado
O estado da educacao num estado intervencionadoO estado da educacao num estado intervencionado
O estado da educacao num estado intervencionadoPedro Barreiros
 
Mivc dayana wagner
Mivc dayana wagnerMivc dayana wagner
Mivc dayana wagnerDayanaWag
 
Double page spread analysis
Double page spread analysisDouble page spread analysis
Double page spread analysisMorganClough
 
كم أحبك ياربي
كم أحبك ياربي كم أحبك ياربي
كم أحبك ياربي iam-muslim
 
Npe thursday talk 3 27-13 agenda
Npe thursday talk 3 27-13 agendaNpe thursday talk 3 27-13 agenda
Npe thursday talk 3 27-13 agendaugradpakistan
 
Joyas del archivo. FC Barcelona
Joyas del archivo. FC BarcelonaJoyas del archivo. FC Barcelona
Joyas del archivo. FC Barcelonacesalo79
 
Mencipta%20link%20pada%20google%20docs_new
Mencipta%20link%20pada%20google%20docs_newMencipta%20link%20pada%20google%20docs_new
Mencipta%20link%20pada%20google%20docs_newAthiseshan Balan
 
Greek gods and goddesses
Greek gods and goddessesGreek gods and goddesses
Greek gods and goddessestocoolforyou
 
How To Motivate Just About Anybody
How To Motivate Just About AnybodyHow To Motivate Just About Anybody
How To Motivate Just About AnybodyPhilippa Davies
 
Junior Civitans
Junior CivitansJunior Civitans
Junior Civitansamelia621
 

Viewers also liked (20)

Radio
RadioRadio
Radio
 
Inovadores ESPM
Inovadores ESPMInovadores ESPM
Inovadores ESPM
 
Programa comenius 12,13 1
Programa comenius 12,13 1Programa comenius 12,13 1
Programa comenius 12,13 1
 
Presenting for Results brochure
Presenting for Results brochurePresenting for Results brochure
Presenting for Results brochure
 
slideshare
slideshareslideshare
slideshare
 
Treball en web
Treball en webTreball en web
Treball en web
 
Slae zambrano
Slae zambranoSlae zambrano
Slae zambrano
 
九五聯盟 信用卡定期定額扣款授權書
九五聯盟 信用卡定期定額扣款授權書九五聯盟 信用卡定期定額扣款授權書
九五聯盟 信用卡定期定額扣款授權書
 
O estado da educacao num estado intervencionado
O estado da educacao num estado intervencionadoO estado da educacao num estado intervencionado
O estado da educacao num estado intervencionado
 
Mivc dayana wagner
Mivc dayana wagnerMivc dayana wagner
Mivc dayana wagner
 
Double page spread analysis
Double page spread analysisDouble page spread analysis
Double page spread analysis
 
كم أحبك ياربي
كم أحبك ياربي كم أحبك ياربي
كم أحبك ياربي
 
Npe thursday talk 3 27-13 agenda
Npe thursday talk 3 27-13 agendaNpe thursday talk 3 27-13 agenda
Npe thursday talk 3 27-13 agenda
 
Joyas del archivo. FC Barcelona
Joyas del archivo. FC BarcelonaJoyas del archivo. FC Barcelona
Joyas del archivo. FC Barcelona
 
Mencipta%20link%20pada%20google%20docs_new
Mencipta%20link%20pada%20google%20docs_newMencipta%20link%20pada%20google%20docs_new
Mencipta%20link%20pada%20google%20docs_new
 
Certificado oceanet
Certificado oceanetCertificado oceanet
Certificado oceanet
 
Greek gods and goddesses
Greek gods and goddessesGreek gods and goddesses
Greek gods and goddesses
 
How To Motivate Just About Anybody
How To Motivate Just About AnybodyHow To Motivate Just About Anybody
How To Motivate Just About Anybody
 
Junior Civitans
Junior CivitansJunior Civitans
Junior Civitans
 
Planning
PlanningPlanning
Planning
 

Similar to CSE341: Programming Languages Lecture 4 - Records, Datatypes, and Case Expressions

Improving Document Clustering by Eliminating Unnatural Language
Improving Document Clustering by Eliminating Unnatural LanguageImproving Document Clustering by Eliminating Unnatural Language
Improving Document Clustering by Eliminating Unnatural LanguageJinho Choi
 
Using Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUUsing Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUSkills Matter
 
Data Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxData Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxtheodorelove43763
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Examshishamrizvi
 
chapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture noteschapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture noteskavitamittal18
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxafsheenfaiq2
 
Ti1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming LinguisticsTi1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming LinguisticsEelco Visser
 
12TypeSystem.pdf
12TypeSystem.pdf12TypeSystem.pdf
12TypeSystem.pdfMdAshik35
 
IE: Named Entity Recognition (NER)
IE: Named Entity Recognition (NER)IE: Named Entity Recognition (NER)
IE: Named Entity Recognition (NER)Marina Santini
 
OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsShanmuganathan C
 
Cs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer KeyCs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer Keyappasami
 
Declare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionDeclare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionEelco Visser
 
11 Unit 1 Chapter 03 Data Handling
11   Unit 1 Chapter 03 Data Handling11   Unit 1 Chapter 03 Data Handling
11 Unit 1 Chapter 03 Data HandlingPraveen M Jigajinni
 
python full notes data types string and tuple
python full notes data types string and tuplepython full notes data types string and tuple
python full notes data types string and tupleSukhpreetSingh519414
 
MACHINE-DRIVEN TEXT ANALYSIS
MACHINE-DRIVEN TEXT ANALYSISMACHINE-DRIVEN TEXT ANALYSIS
MACHINE-DRIVEN TEXT ANALYSISMassimo Schenone
 

Similar to CSE341: Programming Languages Lecture 4 - Records, Datatypes, and Case Expressions (20)

Syntax
SyntaxSyntax
Syntax
 
Erlang session1
Erlang session1Erlang session1
Erlang session1
 
Python ppt_118.pptx
Python ppt_118.pptxPython ppt_118.pptx
Python ppt_118.pptx
 
Improving Document Clustering by Eliminating Unnatural Language
Improving Document Clustering by Eliminating Unnatural LanguageImproving Document Clustering by Eliminating Unnatural Language
Improving Document Clustering by Eliminating Unnatural Language
 
Using Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUUsing Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPU
 
Data Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxData Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docx
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
 
chapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture noteschapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture notes
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
 
Ti1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming LinguisticsTi1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming Linguistics
 
12TypeSystem.pdf
12TypeSystem.pdf12TypeSystem.pdf
12TypeSystem.pdf
 
IE: Named Entity Recognition (NER)
IE: Named Entity Recognition (NER)IE: Named Entity Recognition (NER)
IE: Named Entity Recognition (NER)
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
 
OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objects
 
Cs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer KeyCs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer Key
 
Declare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionDeclare Your Language: Syntax Definition
Declare Your Language: Syntax Definition
 
Lisp and scheme i
Lisp and scheme iLisp and scheme i
Lisp and scheme i
 
11 Unit 1 Chapter 03 Data Handling
11   Unit 1 Chapter 03 Data Handling11   Unit 1 Chapter 03 Data Handling
11 Unit 1 Chapter 03 Data Handling
 
python full notes data types string and tuple
python full notes data types string and tuplepython full notes data types string and tuple
python full notes data types string and tuple
 
MACHINE-DRIVEN TEXT ANALYSIS
MACHINE-DRIVEN TEXT ANALYSISMACHINE-DRIVEN TEXT ANALYSIS
MACHINE-DRIVEN TEXT ANALYSIS
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

CSE341: Programming Languages Lecture 4 - Records, Datatypes, and Case Expressions

  • 1. CSE341: Programming Languages Lecture 4 Records (“each of”), Datatypes (“one of”), Case Expressions Dan Grossman Fall 2011
  • 2. Review • Done: functions, tuples, lists, local bindings, options • Done: syntax vs. semantics, environments, mutation-free • Today: Focus on compound types – New feature: records • New concept: syntactic sugar (tuples are records) – New features: datatypes, constructors, case expressions Fall 2011 CSE341: Programming Languages 2
  • 3. How to build bigger types • Already know: – Have various base types like int bool unit char – Ways to build (nested) compound types: tuples, lists, options • Today: more ways to build compound types • First: 3 most important type building blocks in any language – “Each of”: A t value contains values of each of t1 t2 … tn – “One of”: A t value contains values of one of t1 t2 … tn – “Self reference”: A t value can refer to other t values Remarkable: A lot of data can be described with just these building blocks Note: These are not the common names for these concepts Fall 2011 CSE341: Programming Languages 3
  • 4. Examples • Tuples build each-of types – int * bool contains an int and a bool • Options build one-of types – int option contains an int or it contains no data • Lists use all three building blocks – int list contains an int and another int list or it contains no data • And of course we can nest compound types – ((int * int) option) * (int list list)) option Fall 2011 CSE341: Programming Languages 4
  • 5. Rest of today • Another way to build each-of types in ML – Records: have named fields – Connection to tuples and idea of syntactic sugar • A way to build and use our own one-of types in ML – For example, a type that contains and int or a string – Will lead to pattern-matching (more next lecture), one of ML’s coolest and strangest-to-Java-programmers features – How OOP does one-of types discussed later in course Fall 2011 CSE341: Programming Languages 5
  • 6. Records Record values have fields (any name) holding values {f1 = v1, …, fn = vn} Record types have fields (and name) holding types {f1 : t1, …, fn : tn} The order of fields in a record value or type never matters – REPL alphabetizes fields just for consistency Building records: {f1 = e1, …, fn = en} Accessing components: #myfieldname e (Evaluation rules and type-checking as expected) Fall 2011 CSE341: Programming Languages 6
  • 7. Example {name = “Amelia”, id = 41123 - 12} Evaluates to {id = 41111, name = “Amelia”} And has type {id : int, name : string} If some expression such as a variable x has this type, then get fields with: #id x #name x Note we didn’t have to declare any record types – The same program could also make a {id=true,ego=false} of type {id:bool,ego:bool} Fall 2011 CSE341: Programming Languages 7
  • 8. By name vs. by position • Little difference between (4,7,9) and {f=4,g=7,h=9} – Tuples a little shorter – Records a little easier to remember “what is where” – Generally a matter of taste, but for many (6? 8? 12?) fields, a record is usually a better choice • A common decision for a construct’s syntax is whether to refer to things by position (as in tuples) or by some (field) name (as with records) – A common hybrid is like with Java method arguments (and ML functions as used so far): • Caller uses position • Callee uses variables • Could totally do it differently; some languages have Fall 2011 CSE341: Programming Languages 8
  • 9. The truth about tuples Last week we gave tuples syntax, type-checking rules, and evaluation rules But we could have done this instead: – Tuple syntax is just a different way to write certain records – (e1,…,en) is another way of writing {1=e1,…,n=en} – t1*…*tn is another way of writing {1:t1,…,n:tn} – In other words, records with field names 1, 2, … In fact, this is how ML actually defines tuples – Other than special syntax in programs and printing, they don’t exist – You really can write {1=4,2=7,3=9}, but it’s bad style Fall 2011 CSE341: Programming Languages 9
  • 10. Syntactic sugar “Tuples are just syntactic sugar for records with fields named 1, 2, … n” • Syntactic: Can describe the semantics entirely by the corresponding record syntax • Sugar: They make the language sweeter  Will see many more examples of syntactic sugar – They simplify understanding the language – They simplify implementing the language Why? Because there are fewer semantics to worry about even though we have the syntactic convenience of tuples Fall 2011 CSE341: Programming Languages 10
  • 11. Datatype bindings A “strange” (?) and totally awesome (!) way to make one-of types: – A datatype binding datatype mytype = TwoInts of int * int | Str of string | Pizza • Adds a new type mytype to the environment • Adds constructors to the environment: TwoInts, Str, and Pizza • A constructor is (among other things), a function that makes values of the new type (or is a value of the new type): – TwoInts : int * int -> mytype – Str : string -> mytype – Pizza : mytype Fall 2011 CSE341: Programming Languages 11
  • 12. The values we make datatype mytype = TwoInts of int * int | Str of string | Pizza • Any value of type mytype is made from one of the constructors • The value contains: − A “tag” for “which constructor” (e.g., TwoInts) − The corresponding data (e.g., (7,9)) − Examples: − TwoInts(3+4,5+4) evaluates to TwoInts(7,9) − Str(if true then “hi” else “bye”) evaluates to Str(“hi”) − Pizza is a value Fall 2011 CSE341: Programming Languages 12
  • 13. Using them So we know how to build datatype values; need to access them There are two aspects to accessing a datatype value 1. Check what variant it is (what constructor made it) 2. Extract the data (if that variant has any) Notice how our other one-of types used functions for this: • null and iSome check variants • hd, tl, and valOf extract data (raise exception on wrong variant) ML could have done the same for datatype bindings – For example, functions like “isStr” and “getStrData” – Instead it did something better Fall 2011 CSE341: Programming Languages 13
  • 14. Case ML combines the two aspects of accessing a one-of value with a case expression and pattern-matching – Pattern-matching much more general/powerful (lecture 5) Example: fun f x = (* f has type mytype -> int *) case x of Pizza => 3 | TwoInts(i1,i2) => i1+i2 | Str s => String.size s • A multi-branch conditional to pick branch based on variant • Extracts data and binds to variables local to that branch • Type-checking: all branches must have same type • Evaluation: evaluate between case … of and right branch Fall 2011 CSE341: Programming Languages 14
  • 15. Patterns In general the syntax is: case e0 of p1 => e1 | p2 => e2 … | pn => en For today, each pattern is a constructor name followed by the right number of variables (i.e., C or C x or C(x,y) or …) – Syntactically most patterns (all today) look like expressions – But patterns are not expressions • We do not evaluate them • We see if the result of e0 matches them Fall 2011 CSE341: Programming Languages 15
  • 16. Why this way is better 0. You can use pattern-matching to write your own testing and data-extractions functions if you must – But don’t do that on your homework 1. You can’t forget a case (inexhaustive pattern-match a warning) 2. You can’t duplicate a case (a type-checking error) 3. You won’t forget to test the variant correctly and get an exception (like hd []) 4. Pattern-matching can be generalized and made more powerful, leading to elegant and concise code Fall 2011 CSE341: Programming Languages 16
  • 17. Useful examples Let’s fix the fact that our only example datatype so far was silly… • Enumerations, including carrying other data datatype suit = Club | Diamond | Heart | Spade datatype card_value = Jack | Queen | King | Ace | Num of int • Alternate ways of representing data about things (or people ) datatype id = StudentNum of int | Name of string * (string option) * string Fall 2011 CSE341: Programming Languages 17
  • 18. Don’t do this Unfortunately, bad training and languages that make one-of types inconvenient lead to common bad style where each-of types are used where one-of types are the right tool (* use the studen_num and ignore other fields unless the student_num is ~1 *) { student_num : int, first : string, middle : string option, last : string } • Approach gives up all the benefits of the language enforcing every value is one variant, you don’t forget branches, etc. • And it makes it less clear what you are doing Fall 2011 CSE341: Programming Languages 18
  • 19. That said… But if instead, the point is that every “person” in your program has a name and maybe a student number, then each-of is the way to go: { student_num : int option, first : string, middle : string option, last : string } Fall 2011 CSE341: Programming Languages 19
  • 20. Expression Trees A more exciting (?) example of a datatype, using self-reference datatype exp = Constant of int | Negate of exp | Add of exp * exp | Multiply of exp * exp An expression in ML of type exp: Add (Constant (10+9), Negate (Constant 4)) How to picture the resulting value in your head: Add Constant Negate 19 Constant 4 Fall 2011 CSE341: Programming Languages 20
  • 21. Recursion Not surprising: Functions over recursive datatypes are usually recursive fun eval e = case e of Constant i => i | Negate e2 => ~ (eval e2) | Add(e1,e2) => (eval e1) + (eval e2) | Multiply(e1,e2) => (eval e1) * (eval e2) Fall 2011 CSE341: Programming Languages 21