EECS 700 Functional Programming

Size: px
Start display at page:

Download "EECS 700 Functional Programming"

Transcription

1 EECS 700 Functional Programming Dr. Andy Gill University of Kansas February 16, / 41

2 Parsing A parser is a program that analyses a piece of text to determine its syntactic structure. The expression * 3 means / 41

3 The Parser Type In a functional language such as Haskell, parsers can naturally be viewed as functions. type Parser = String -> Tree A parser is a function that takes a string and returns some form of tree. Tree could be defined data Tree = Val Int Add Tree Tree Mul Tree Tree 3 / 41

4 However, a parser might not require all of its input string, so we also return any unused input: type Parser = String -> (Tree,String) A string might not be possible to parse, so we generalize to an optional result: type Parser = String -> Maybe (Tree,String) Finally, a parser might not always produce a tree, so we generalize to a value of any type: type Parser a = String -> Maybe (a,string) 4 / 41

5 Basic Parsers The parser item fails if the input is empty, and consumes the first character otherwise: item :: Parser Char item = \ inp -> case inp of [] -> Nothing (x:xs) -> Just (x,xs) 5 / 41

6 Basic Parsers (2) The parser failure always fails: failure :: Parser a failure = \ inp -> Nothing 6 / 41

7 Basic Parsers (3) The parser return v always succeeds, returning the value v without consuming any input: return :: a -> Parser a return v = \ inp -> Just (v,inp) 7 / 41

8 The parser p +++ q behaves as the parser p if it succeeds, and as the parser q otherwise: (+++) :: Parser a -> Parser a -> Parser a p +++ q = \ inp -> case p inp of Nothing -> q inp Just (v,out) -> Just (v,out) The function parse applies a parser to a string: parse :: Parser a -> String -> Maybe (a,string) parse p inp = p inp 8 / 41

9 Examples The behavior of the five parsing primitives can be illustrated with some simple examples: > parse item "" Nothing > parse item "abc" Just ( a,"bc") 9 / 41

10 > parse failure "abc" Nothing > parse (return 1) "abc" Just (1,"abc") > parse (item +++ return d ) "abc" Just ( a,"bc") > parse (failure +++ return d ) "abc" Just ( d,"abc") 10 / 41

11 Sequencing parsers Can a sequence of parsers can be combined as a single composite parser using the keyword do? p :: Parser (Char,Char) p = do x <- item item y <- item return (x,y) Yes, if we can figure out how to write >>= 11 / 41

12 Monads Both IO and Parser are Monads. Do not be scared by the name. There are many more Monads. All monads have the type XYZ a. All monads have a way of building a side-effect free XYZ a from an a, called return. All monads have a way of sequencing XYZ, called >>= Thats all there is! 12 / 41

13 Sequencing parsers (>>=) :: Parser a -> (a -> Parser b) -> Parser b p1 >>= p2 = \ inp -> case p1 inp of Nothing -> Nothing Just (v,out) -> p2 v out If the first parser fails, then fail, else run the second parser, using the result of the first parser. 13 / 41

14 Sequencing parsers If we can tell do to use our new >>=, then we can write p :: Parser (Char,Char) p = do x <- item item y <- item return (x,y) > parse p "abcdef" Just ((a,c),"def") > parse p "ab" Nothing Alas, this overloading only words for data, and Parser is not data. 14 / 41

15 Abstract Parser Our solution is put the Parser function inside a data constructor. data Parser a = P (String -> Maybe (a,string)) -- Deconstructs a Parser to its function runp :: Parser a -> (String -> Maybe (a,string)) runp (P p) = p We need to rewrite our (small number of) primitives to use this box. There is always a tension between using type, and making things simple and concrete, and using data, complicating things slightly, but using the abstraction. Abstractions keep you honest! 15 / 41

16 item :: Parser Char item = P (\ inp -> case inp of [] -> Nothing (x:xs) -> Just (x,xs)) failure :: Parser a failure = P (\ inp -> Nothing) (+++) :: Parser a -> Parser a -> Parser a p +++ q = P (\ inp -> case runp p inp of Nothing -> runp q inp Just (v,out) -> Just (v,out)) parse :: Parser a -> String -> Maybe (a,string) parse p = \ inp -> runp p inp 16 / 41

17 The keyword instance is used to tell the compiler that Parser is a Monad. instance Monad Parser where -- (>>=) :: Parser a -> (a -> Parser b) -> Parser b p1 >>= p2 = P (\ inp -> case runp p1 inp of Nothing -> Nothing Just (v,out) -> runp (p2 v) out) -- return :: a -> Parser a return v = P (\ inp -> Just (v,inp)) 17 / 41

18 Sequencing parsers With this instance in place, we can use the do notation p :: Parser (Char,Char) p = do x <- item item y <- item return (x,y) > parse p "abcdef" Just ((a,c),"def") > parse p "ab" Nothing 18 / 41

19 Derived Primitives Parsing a character that satisfies a predicate: sat :: (Char -> Bool) -> Parser Char sat p = do x <- item if p x then return x else failure We are building on our primitives, and the Parser abstraction is being used transparently. 19 / 41

20 Parsing a digit and specific characters: digit :: Parser Char digit = sat isdigit char :: Char -> Parser Char char x = sat (x ==) 20 / 41

21 Applying a parser zero or more times: many :: Parser a -> Parser [a] many p = many1 p +++ return [] Applying a parser one or more times: many1 :: Parser a -> Parser [a] many1 p = do v <- p vs <- many p return (v:vs) 21 / 41

22 Finally, we can now define a parser that consumes a list of one or more digits from a string: p :: Parser String p = do char [ d <- digit ds <- many (do char, digit) char ] return (d:ds) 22 / 41

23 For example: Note: > parse p "[1,2,3,4]" [("1234","")] > parse p "[1,2,3,4" Nothing More sophisticated parsing libraries can indicate and/or recover from errors in the input string. 23 / 41

24 Arithmetic Expressions Consider a simple form of expressions built up from single digits using the operations of addition + and multiplication *, together with parentheses. We also assume that: * and + associate to the right; * has higher priority than / 41

25 Formally, the syntax of such expressions is defined by the following context free grammar: expr term + expr term term factor term factor factor digit ( expr ) digit / 41

26 However, for reasons of efficiency, it is important to factorize the rules for expr and term: Note: expr term ( + expr ɛ ) term factor ( term ɛ ) factor digit ( expr ) digit The symbol ɛ denotes the empty string. 26 / 41

27 It is now easy to translate the grammar into a parser that evaluates expressions, by simply rewriting the grammar rules using the parsing primitives. That is, we have: expr :: Parser Int expr = do t <- term do char + e <- expr return (t + e) +++ return t 27 / 41

28 term :: Parser Int term = do f <- factor do char * t <- term return (f * t) +++ return f factor :: Parser Int factor = do d <- digit return (digittoint d) +++ do char ( e <- expr char ) return e 28 / 41

29 Finally, if we define eval :: String -> Int eval xs = case parse expr xs of Just (v,_) -> v Nothing -> error "failed" then we try out some examples: > eval "2*3+4" 10 > eval "2*(3+4)" 14 > eval "1(2)" Error 29 / 41

30 Monads Both IO and Parser are Monads. Do not be scared by the name. There are many more Monads. All monads have the type XYZ a. All monads have a way of building a side-effect free XYZ a from an a, called return. All monads have a way of sequencing XYZ, called bind Thats all there is! 30 / 41

31 Monads Both IO and Parser are Monads. Do not be scared by the name. There are many more Monads. All monads have the type XYZ a. All monads have a way of building a side-effect free XYZ a from an a, called return. All monads have a way of sequencing XYZ, called bind Thats all there is! 31 / 41

32 Monads Laws How do we enforce sequencing? Right identity m >>= (\ a -> return a) = m do a <- m return a do a <- m return a = do m = m 32 / 41

33 Monads Laws How do we enforce sequencing? Left identity return v >>= (\ a ->...) = let a = v in... do a <- return v = do let a = v do a <- return v = let a = v... in do / 41

34 Monads Laws How do we enforce sequencing? Associativity (m >>= f) >>= g = m >>= (\ x -> f x >>= g) do y <- do x <- m = do x <- m f x do y <- f x do y <- do x <- m = do x <- m f x y <- f x / 41

35 Monads Laws in Action f :: IO Char f = do a <- getchar return a By right identity f :: IO Char f = getchar 35 / 41

36 Monads Laws in Action g :: IO () g = do a <- return 4 print a By left identity OR g :: IO () g = do let a = 4 print a g :: IO () g = let a = 4 in print a 36 / 41

37 Monads Laws in Action h :: IO () h = do y <- do x <- getchar return (toupper x) print y By associativity h :: IO () h = do x <- getchar y <- return (toupper x) print y 37 / 41

38 Exception Monads instance Monad Maybe where -- return :: a -> Maybe a return a = Just a -- (>>=) :: Maybe a -- -> (a -> Maybe b) -- -> Maybe b m >>= k = case m of Nothing -> Nothing Just v -> k v -- fail :: String -> Maybe a fail msg = Nothing 38 / 41

39 Exception Monad Example gooddiv :: Int -> Int -> Maybe Int gooddiv x y y == 0 = fail "div by zero" otherwise = return (x div y) silly :: Int -> Int -> Int -> Maybe Int silly a b c = do v1 <- 32 gooddiv a v2 <- 16 gooddiv b v3 <- 9 gooddiv c return (a + b + c) 39 / 41

40 catch :: Maybe a -> Maybe a -> Maybe a catch (Just a) _ = Just a catch Nothing other = other -- Alternate way of writing catch catch :: Maybe a -> Maybe a -> Maybe a catch good@(just _) _ = good catch Nothing other = other runmaybe :: Maybe a -> a runmaybe Nothing = error "Nothing" runmaybe (Just v) = v 40 / 41

41 > runmaybe (30 gooddiv 9) 3 > runmaybe (30 gooddiv 0) Error > runmaybe ((30 gooddiv 0) catch return 1234) / 41

CSCE 314 Programming Languages. Functional Parsers

CSCE 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 information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Functional Parsers

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Functional Parsers 1 CSCE 314: Programming Languages Dr. Flemming Andersen Functional Parsers 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 information

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics National Institute of Informatics May 31, June 7, June 14, 2010 All Right Reserved. Outline I 1 Parser Type 2 Monad Parser Monad 3 Derived Primitives 4 5 6 Outline Parser Type 1 Parser Type 2 3 4 5 6 What

More information

CSCE 314 Programming Languages. Monadic Parsing

CSCE 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 information

CSCE 314 Programming Languages. Monadic Parsing

CSCE 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 information

CIS552: Advanced Programming

CIS552: Advanced Programming CIS552: Advanced Programming Handout 8 What is a Parser? A parser is a program that analyzes a piece of text to deine its structure (and, typically, returns a tree representing this structure). The World

More information

Monadic Parsing. 1 Chapter 13 in the book Programming in Haskell (2nd ed.) by. 2 Chapters 10 and 16 in the book Real World Haskell by Bryan

Monadic Parsing. 1 Chapter 13 in the book Programming in Haskell (2nd ed.) by. 2 Chapters 10 and 16 in the book Real World Haskell by Bryan Source The source material for this lecture is EDAF/N40: Functional Programming Jacek Malec Dept. of Computer Science, Lund University, Sweden May 7th, 2018 1 Chapter 13 in the book Programming in Haskell

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Final Review Part I Dr. Hyunyoung Lee 1 Programming Language Characteristics Different approaches to describe computations, to instruct computing devices E.g., Imperative,

More information

University of Utrecht. 1992; Fokker, 1995), the use of monads to structure functional programs (Wadler,

University of Utrecht. 1992; Fokker, 1995), the use of monads to structure functional programs (Wadler, J. Functional Programming 1 (1): 1{000, January 1993 c 1993 Cambridge University Press 1 F U N C T I O N A L P E A R L S Monadic Parsing in Haskell Graham Hutton University of Nottingham Erik Meijer University

More information

Informatics 1 Functional Programming 19 Tuesday 23 November IO and Monads. Philip Wadler University of Edinburgh

Informatics 1 Functional Programming 19 Tuesday 23 November IO and Monads. Philip Wadler University of Edinburgh Informatics 1 Functional Programming 19 Tuesday 23 November 2010 IO and Monads Philip Wadler University of Edinburgh The 2010 Informatics 1 Competition Sponsored by Galois (galois.com) List everyone who

More information

Fusion-powered EDSLs

Fusion-powered EDSLs Fusion-powered EDSLs Philippa Cowderoy flippa@flippac.org Fusion-powered EDSLs p. Outline What is fusion? Anatomy of an EDSL Shallow vs deep embedding Examples: Identity & State monads Self-analysing EDSL

More information

The Worker/Wrapper Transformation

The Worker/Wrapper Transformation The Worker/Wrapper Transformation Andy Gill 1 Graham Hutton 2 1 The University of Kansas 2 The University of Nottingham March 26th, 2009 Andy Gill, Graham Hutton The Worker/Wrapper Transformation March

More information

Informatics 1 Functional Programming Lectures 15 and 16. IO and Monads. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lectures 15 and 16. IO and Monads. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lectures 15 and 16 IO and Monads Don Sannella University of Edinburgh Part I The Mind-Body Problem The Mind-Body Problem Part II Commands Print a character putchar

More information

Parsing Expressions. Slides by Koen Lindström Claessen & David Sands

Parsing Expressions. Slides by Koen Lindström Claessen & David Sands Parsing Expressions Slides by Koen Lindström Claessen & David Sands Expressions Such as 5*2+12 17+3*(4*3+75) Can be modelled as a datatype data Expr = Num Int Add Expr Expr Mul Expr Expr Showing and Reading

More information

The Worker/Wrapper Transformation

The Worker/Wrapper Transformation The Worker/Wrapper Transformation Andy Gill 1 Graham Hutton 2 1 Galois, Inc. 2 University of Nottingham February 6, 2008 Andy Gill, Graham Hutton The Worker/Wrapper Transformation February 6, 2008 1 /

More information

CSCE 314 Programming Languages Functors, Applicatives, and Monads

CSCE 314 Programming Languages Functors, Applicatives, and Monads CSCE 314 Programming Languages Functors, Applicatives, and Monads Dr. Hyunyoung Lee 1 Motivation Generic Functions A common programming pattern can be abstracted out as a definition. For example: inc ::

More information

CS 209 Functional Programming

CS 209 Functional Programming CS 209 Functional Programming Lecture 03 - Intro to Monads Dr. Greg Lavender Department of Computer Science Stanford University "The most important thing in a programming language is the name. A language

More information

Syntax and Grammars 1 / 21

Syntax and Grammars 1 / 21 Syntax and Grammars 1 / 21 Outline What is a language? Abstract syntax and grammars Abstract syntax vs. concrete syntax Encoding grammars as Haskell data types What is a language? 2 / 21 What is a language?

More information

Lecture C-10: Parser Combinators - Introduction

Lecture C-10: Parser Combinators - Introduction Lecture C-10: Parser Combinators - Introduction USCS 2015 Doaitse Swierstra Utrecht University July 6-17, 2015 1. Domain Specific Languages 2 Domain Specific Languages 1 A DSL is a programming language

More information

Expressions. Parsing Expressions. Showing and Reading. Parsing. Parsing Numbers. Expressions. Such as. Can be modelled as a datatype

Expressions. Parsing Expressions. Showing and Reading. Parsing. Parsing Numbers. Expressions. Such as. Can be modelled as a datatype Expressions Parsing Expressions Such as 5*2+12 17+3*(4*3+75) Can be modelled as a datatype Add Expr Expr Mul Expr Expr Slides by Koen Lindström Claessen & David Sands Showing and Reading We have seen how

More information

Introduction to Haskell

Introduction to Haskell Introduction to Haskell Matt Mullins Texas A&M Computing Society October 6, 2009 Matt Mullins (TACS) Introduction to Haskell October 6, 2009 1 / 39 Outline Introduction to Haskell Functional Programming

More information

Monads seen so far: IO vs Gen

Monads seen so far: IO vs Gen Monads David Sands Monads seen so far: IO vs Gen IO A Gen A Instructions to build a value of type A by interacting with the operating system Instructions to create a random value of type A Run by the ghc

More information

Monads. Functional Programming (CS4011) Monads

Monads. Functional Programming (CS4011) Monads Monads Functional Programming (CS4011) Andrew Butterfield Glenn Strong Foundations & Methods Group, Discipline of Software Systems Trinity College, University of Dublin {Andrew.Butterfield,Glenn.Strong}@cs.tcd.ie

More information

Standard prelude. Appendix A. A.1 Classes

Standard 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 information

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Haskell 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 information

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

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type. OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compile-time Static 1. Enter expression 2. ML infers a type Exec-time Dynamic Types 3. ML crunches expression down to a value 4. Value

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Declaring Types and Classes Dr. Hyunyoung Lee 1 Outline Declaring Data Types Class and Instance Declarations 2 Defining New Types Three constructs for defining types:

More information

INTRODUCTION TO FUNCTIONAL PROGRAMMING

INTRODUCTION TO FUNCTIONAL PROGRAMMING INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham adapted by Gordon Uszkay 1 What is Functional Programming? Opinions differ, and it is difficult to give a precise definition,

More information

Talen en Compilers. Jurriaan Hage , period 2. November 13, Department of Information and Computing Sciences Utrecht University

Talen en Compilers. Jurriaan Hage , period 2. November 13, Department of Information and Computing Sciences Utrecht University Talen en Compilers 2017-2018, period 2 Jurriaan Hage Department of Information and Computing Sciences Utrecht University November 13, 2017 1. Introduction 1-1 This lecture Introduction Course overview

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL. Chapter 2 - First Steps PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

More information

Programming Languages

Programming Languages Programming Languages Andrea Flexeder Chair for Theoretical Computer Science Prof. Seidl TU München winter term 2010/2011 Lecture 10 Side-Effects Main Points you should get: Why monads? What is a monad?

More information

Monads. COS 441 Slides 16

Monads. COS 441 Slides 16 Monads COS 441 Slides 16 Last time: Agenda We looked at implementation strategies for languages with errors, with printing and with storage We introduced the concept of a monad, which involves 3 things:

More information

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18)

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18) Advanced Programming Handout 7 Monads and Friends (SOE Chapter 18) The Type of a Type In previous chapters we discussed: Monomorphic types such as Int, Bool, etc. Polymorphic types such as [a], Tree a,

More information

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group Advanced Type System Features Tom Schrijvers Leuven Haskell User Group Data Recursion Genericity Schemes Expression Problem Monads GADTs DSLs Type Type Families Classes Lists and Effect Free Other Handlers

More information

Thoughts on Assignment 4 Haskell: Flow of Control

Thoughts on Assignment 4 Haskell: Flow of Control Thoughts on Assignment 4 Haskell: Flow of Control CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 27, 2017 Glenn G. Chappell Department of Computer

More information

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

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Principles of Programming Languages 2017W, Functional Programming

Principles of Programming Languages 2017W, Functional Programming Principles of Programming Languages 2017W, Functional Programming Assignment 3: Lisp Machine (16 points) Lisp is a language based on the lambda calculus with strict execution semantics and dynamic typing.

More information

A general introduction to Functional Programming using Haskell

A general introduction to Functional Programming using Haskell A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell

More information

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without previous written authorization. 1 2 The simplest way to create

More information

Monads. Bonus lecture 2017 David Sands

Monads. Bonus lecture 2017 David Sands Monads Bonus lecture 2017 David Sands Our version of the story, so far. Monad is the class of instructions. Instructions can be built using do notation. We have seen two kinds of instructions i.e. two

More information

IO Monad (3D) Young Won Lim 1/18/18

IO Monad (3D) Young Won Lim 1/18/18 Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Monads and all that I. Monads. John Hughes Chalmers University/Quviq AB

Monads and all that I. Monads. John Hughes Chalmers University/Quviq AB Monads and all that I. Monads John Hughes Chalmers University/Quviq AB Binary Trees in Haskell data Tree a = Leaf a Branch (Tree a) (Tree a) deriving (Eq,Show) Cf Coq: Inductive tree (A:Set) : Set := leaf

More information

Informatics 1 Functional Programming Lecture 5. Function properties. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 5. Function properties. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lecture 5 Function properties Don Sannella University of Edinburgh Part I Booleans and characters Boolean operators not :: Bool -> Bool (&&), ( ) :: Bool -> Bool ->

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

ML Built-in Functions

ML Built-in Functions ML Built-in Functions Since ML is a functional programming language, many of its built-in functions are concerned with function application to objects and structures. In ML, built-in functions are curried

More information

IO Monad (3C) Young Won Lim 1/6/18

IO Monad (3C) Young Won Lim 1/6/18 Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Haskell Types, Classes, and Functions, Currying, and Polymorphism

Haskell Types, Classes, and Functions, Currying, and Polymorphism 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Types, Classes, and Functions, Currying, and Polymorphism 2 Types A type is a collection of related values. For example, Bool contains the

More information

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

More information

State Monad (3D) Young Won Lim 9/25/17

State Monad (3D) Young Won Lim 9/25/17 Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

ASTs, Objective CAML, and Ocamlyacc

ASTs, Objective CAML, and Ocamlyacc ASTs, Objective CAML, and Ocamlyacc Stephen A. Edwards Columbia University Fall 2012 Parsing and Syntax Trees Parsing decides if the program is part of the language. Not that useful: we want more than

More information

Bindings & Substitution

Bindings & Substitution Bindings & Substitution Even in our simple language, we encounter repeated expressions. 1 {* {+ 4 2} {+ 4 2}} There are several reasons to eliminate duplicated code. It introduces a redundant computation.

More information

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012 News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A

More information

College Functors, Applicatives

College Functors, Applicatives College 2016-2017 Functors, Applicatives Wouter Swierstra with a bit of Jurriaan Hage Utrecht University Contents So far, we have seen monads define a common abstraction over many programming patterns.

More information

Programming in Haskell Aug Nov 2015

Programming in Haskell Aug Nov 2015 Programming in Haskell Aug Nov 2015 LECTURE 23 NOVEMBER 12, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Summary of IO Actions of type IO t1, t1 -> IO t2, t1 -> t2 -> IO t3 etc. As opposed to pure functions

More information

CS 360: Programming Languages Lecture 10: Introduction to Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell CS 360: Programming Languages Lecture 10: Introduction to Haskell Geoffrey Mainland Drexel University Thursday, February 5, 2015 Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia

More information

A Simple Syntax-Directed Translator

A Simple Syntax-Directed Translator Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called

More information

CSCE 314 Programming Languages. Type System

CSCE 314 Programming Languages. Type System CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be

More information

Chapter 11 - The Countdown Problem

Chapter 11 - The Countdown Problem PROGRAMMING IN HASKELL Chapter 11 - The Countdown Problem 1 What Is Countdown? A popular quiz programme on British television that has been running since 1982. Based upon an original French version called

More information

CSE3322 Programming Languages and Implementation

CSE3322 Programming Languages and Implementation Monash University School of Computer Science & Software Engineering Exam 2005 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration. 2.

More information

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors Solution sheet 1 Introduction Please note that there can be other solutions than those listed in this document. This is a literate Haskell file which is available as PDF, as well as literate Haskell source

More information

Left to right design 1

Left to right design 1 Left to right design 1 Left to right design The left to right design method suggests that the structure of the program should closely follow the structure of the input. The method is effective when the

More information

INFOB3TC Solutions for the Exam

INFOB3TC Solutions for the Exam Department of Information and Computing Sciences Utrecht University INFOB3TC Solutions for the Exam Johan Jeuring Monday, 13 December 2010, 10:30 13:00 lease keep in mind that often, there are many possible

More information

Functional Logic Programming Language Curry

Functional Logic Programming Language Curry Functional Logic Programming Language Curry Xiang Yin Department of Computer Science McMaster University November 9, 2010 Outline Functional Logic Programming Language 1 Functional Logic Programming Language

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

10/18/18. Outline. Semantic Analysis. Two types of semantic rules. Syntax vs. Semantics. Static Semantics. Static Semantics.

10/18/18. Outline. Semantic Analysis. Two types of semantic rules. Syntax vs. Semantics. Static Semantics. Static Semantics. Outline Semantic Analysis In Text: Chapter 3 Static semantics Attribute grammars Dynamic semantics Operational semantics Denotational semantics N. Meng, S. Arthur 2 Syntax vs. Semantics Syntax concerns

More information

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell: Haskell Programs We re covering material from Chapters 1-2 (and maybe 3) of the textbook. Haskell Fundamentals Prof. Susan Older A Haskell program is a series of comments and definitions. Each comment

More information

CSCE 314 Programming Languages. Interactive Programming: I/O

CSCE 314 Programming Languages. Interactive Programming: I/O CSCE 314 Programming Languages Interactive Programming: I/O Dr. Hyunyoung Lee 1 Introduction To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start

More information

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella Haskell & functional programming, some slightly more advanced stuff Matteo Pradella pradella@elet.polimi.it IEIIT, Consiglio Nazionale delle Ricerche & DEI, Politecnico di Milano PhD course @ UniMi - Feb

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

CSE302: Compiler Design

CSE302: Compiler Design CSE302: Compiler Design Instructor: Dr. Liang Cheng Department of Computer Science and Engineering P.C. Rossin College of Engineering & Applied Science Lehigh University February 20, 2007 Outline Recap

More information

This book is licensed under a Creative Commons Attribution 3.0 License

This book is licensed under a Creative Commons Attribution 3.0 License 6. Syntax Learning objectives: syntax and semantics syntax diagrams and EBNF describe context-free grammars terminal and nonterminal symbols productions definition of EBNF by itself parse tree grammars

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 06: Useful Haskell Syntax, HO Programming Continued o Goodbye to Bare Bones Haskell: Built-in

More information

Calculating Correct Compilers

Calculating Correct Compilers university of copenhagen department of computer science Faculty of Science Calculating Correct Compilers Patrick Bahr1 Graham Hutton2 1 University of Copenhagen, Department of Computer Science paba@diku.dk

More information

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

More information

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou COMP-421 Compiler Design Presented by Dr Ioanna Dionysiou Administrative! Any questions about the syllabus?! Course Material available at www.cs.unic.ac.cy/ioanna! Next time reading assignment [ALSU07]

More information

Standard ML. Data types. ML Datatypes.1

Standard ML. Data types. ML Datatypes.1 Standard ML Data types ML Datatypes.1 Concrete Datatypes The datatype declaration creates new types These are concrete data types, not abstract Concrete datatypes can be inspected - constructed and taken

More information

Programming Languages Fall 2013

Programming Languages Fall 2013 Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

CS422 - Programming Language Design

CS422 - Programming Language Design 1 CS422 - Programming Language Design From SOS to Rewriting Logic Definitions Grigore Roşu Department of Computer Science University of Illinois at Urbana-Champaign In this chapter we show how SOS language

More information

CS 381: Programming Language Fundamentals

CS 381: Programming Language Fundamentals CS 381: Programming Language Fundamentals Summer 2017 Semantics July 12, 2017 Outline What is semantics? Semantics of naming 2 Why do we need semantics? Understand what program constructs do Judge the

More information

Interpreters. Prof. Clarkson Fall Today s music: Step by Step by New Kids on the Block

Interpreters. Prof. Clarkson Fall Today s music: Step by Step by New Kids on the Block Interpreters Prof. Clarkson Fall 2017 Today s music: Step by Step by New Kids on the Block Review Previously in 3110: functional programming modular programming data structures Today: new unit of course:

More information

Term rewriting a primer

Term rewriting a primer Term rewriting a primer Ralf Lämmel Software Languages Team University of Koblenz-Landau http://www.softlang.org/ Some laws for expressions forms X + 0 = X -- Unit of addition X 1 = X -- Unit of multiplication

More information

CS 11 Haskell track: lecture 4. n This week: Monads!

CS 11 Haskell track: lecture 4. n This week: Monads! CS 11 Haskell track: lecture 4 This week: Monads! Monads Have already seen an example of a monad IO monad But similar concepts can be used for a lot of completely unrelated tasks Monads are useful "general

More information

CSE3322 Programming Languages and Implementation

CSE3322 Programming Languages and Implementation Monash University School of Computer Science & Software Engineering Sample Exam 2004 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration.

More information

Compilers and computer architecture From strings to ASTs (2): context free grammars

Compilers and computer architecture From strings to ASTs (2): context free grammars 1 / 1 Compilers and computer architecture From strings to ASTs (2): context free grammars Martin Berger October 2018 Recall the function of compilers 2 / 1 3 / 1 Recall we are discussing parsing Source

More information

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics SE3E03, 2006 1.59 61 Syntax and Semantics Syntax Shape of PL constructs What are the tokens of the language? Lexical syntax, word level How are programs built from tokens? Mostly use Context-Free Grammars

More information

Background Operators (1E) Young Won Lim 7/7/18

Background Operators (1E) Young Won Lim 7/7/18 Background Operators (1E) Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

More information

5. Syntax-Directed Definitions & Type Analysis

5. Syntax-Directed Definitions & Type Analysis 5. Syntax-Directed Definitions & Type Analysis Eva Rose Kristoffer Rose NYU Courant Institute Compiler Construction (CSCI-GA.2130-001) http://cs.nyu.edu/courses/spring15/csci-ga.2130-001/lecture-5.pdf

More information

A Small Interpreted Language

A Small Interpreted Language A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

More information

Lecture 19: Functions, Types and Data Structures in Haskell

Lecture 19: Functions, Types and Data Structures in Haskell The University of North Carolina at Chapel Hill Spring 2002 Lecture 19: Functions, Types and Data Structures in Haskell Feb 25 1 Functions Functions are the most important kind of value in functional programming

More information

Denotational Semantics. Domain Theory

Denotational Semantics. Domain Theory Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning

More information

Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF)

Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF) Chapter 3: Describing Syntax and Semantics Introduction Formal methods of describing syntax (BNF) We can analyze syntax of a computer program on two levels: 1. Lexical level 2. Syntactic level Lexical

More information

Parsing Combinators: Introduction & Tutorial

Parsing Combinators: Introduction & Tutorial Parsing Combinators: Introduction & Tutorial Mayer Goldberg October 21, 2017 Contents 1 Synopsis 1 2 Backus-Naur Form (BNF) 2 3 Parsing Combinators 3 4 Simple constructors 4 5 The parser stack 6 6 Recursive

More information

References. Monadic I/O in Haskell. Digression, continued. Digression: Creating stand-alone Haskell Programs

References. Monadic I/O in Haskell. Digression, continued. Digression: Creating stand-alone Haskell Programs References Monadic I/O in Haskell Jim Royer CIS 352 March 6, 2018 Chapter 18 of Haskell: the Craft of Functional Programming by Simon Thompson, Addison-Wesley, 2011. Chapter 9 of Learn you a Haskell for

More information

Monad class. Example: Lambda laughter. The functional IO problem. EDAN40: Functional Programming Functors and Monads

Monad class. Example: Lambda laughter. The functional IO problem. EDAN40: Functional Programming Functors and Monads Monad class EDAN40: Functional Programming Functors and Monads Jacek Malec Dept. of Computer Science, Lund University, Sweden April 23rd, 2018 Motivation: Separation of pure and impure code Properties

More information

CPS 506 Comparative Programming Languages. Syntax Specification

CPS 506 Comparative Programming Languages. Syntax Specification CPS 506 Comparative Programming Languages Syntax Specification Compiling Process Steps Program Lexical Analysis Convert characters into a stream of tokens Lexical Analysis Syntactic Analysis Send tokens

More information

Part 5 Program Analysis Principles and Techniques

Part 5 Program Analysis Principles and Techniques 1 Part 5 Program Analysis Principles and Techniques Front end 2 source code scanner tokens parser il errors Responsibilities: Recognize legal programs Report errors Produce il Preliminary storage map Shape

More information

CA Compiler Construction

CA Compiler Construction CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must

More information