Functional Programming


 Anthony Patterson
 10 months ago
 Views:
Transcription
1 14 Functional Programming Exercises 14.1 a. 5 5 = 25 b. ((λy.3 + y + z)2) = z = 5 + z c. (λv.(λw.w)(y(λz.z))) 14.2 The results are the same. In part b, where there are two beta reductions, lazy evaluation gives a different order: ((λx.x+2+z)3) = 3+2+z = 5+z Evaluate the following expressions using your Scheme interpreter: (a) #t (b) #f (c) a (d) ((b c) d e) (e) (b c) 14.4 (sum ) = (+ 1 (sum )) = (+ 1 (+ 2 (sum 3 4 5))) = (+ 1 (+ 2 (+ 3 (sum 4 5)))) = (+ 1 (+ 2 (+ 3 (+ 4 (sum 5))))) = (+ 1 (+ 2 (+ 3 (+ 4 (+ 5 (sum ()))))) = (+ 1 (+ 2 (+ 3 (+ 4 (+ 5 0)))))... = (define (elements lst) (if (null? lst) 0 (if (list? (car lst)) (+ (elements (car lst)) (elements (cdr lst))) (+ 1 (elements (cdr lst))) 63
2 FUNCTIONAL PROGRAMMING 14.6 (mexpression (plus (times (variable a) (variable b)) (value 2)) ((a 2) (b 4))) = (+ (* (mexpression (variable a) ((a 2) (b 4))) (mexpression (variable b) ((a 2) (b 4)))) (value 2)) =... = (+ (* 2 4) 2) = (+ 8 2) = Add the following to the case before the else in applybinary: ((lt) ((le) ((eq) ((ne) ((gt) ((ge) (< leftval rightval)) (<= leftval rightval)) (= leftval rightval)) (not (= leftval rightval))) (> leftval rightval)) (>= leftval rightval)) 14.8 (define (massignment statement state) (let ((target (car statement)) (source (cdr statement))) (onion target (mexpression source state) state) )) 14.9 Add the following case before the else in mexpression: ((not) (not (mexpression (cadr expr) state))) Below is a sketch of the essentials of a static type checker for Clite. First, assume the abstract syntax of program and declarations to be: ; Program = (declarations block) ; Declarations = ((v1 t1) (v2 t2)...) ; where vi = variable identifier ; ti = type, i.e., int, bool, float, or char) Because Declarations already has the structure of a Clite TypeMap, a separate typing function to create a TypeMap is unnecessary. Then it is only necessary to implement the typeof function and the various validity functions V. For example: (define (vprogram p) (let ((tm (car p)) (body (cadr p))) (and (vdecls tm) (vstmt body tm)) )) (define (vdecls tm) (if (null? tm) #t (let ((d (caar tm)) (tail (cdr tm))) (if (isin? d tail) #f
3 65 (vdecls tail) )))) (define (isin? id lst) (if (null? lst) #f (if (equal? id (caar lst)) #t (isin? id (cdr lst)) ))) Here, e.g., is the validity check for assignment: (define (vassign s tm) (let ((target (cadr s)) (source (caddr s))) (and (isin? target tm) (vexpr source tm) (equal? (get target tm) (typeof source tm)) ))) Note that because a state and a type map have the same structure, we can use our get function on a TypeMap to retrieve a type. Here are the beginnings of a function typeof: (define (typeof e tm) (let ((kind (car e)) (opnd (cadr e))) (case kind ((value) (boolean? opnd)) ((variable) (get opnd tm)) ((plus minus times div) (typeof opnd)) (else bool) ))) Most of this is summarized in Section , and many of the missing pieces are included in earlier exercises. The challenge here is to complete the implementation of the Clite lnterpreter in Scheme and then demonstrate its completeness by interpreting a variety of abstract Clite programs Using a caret to denote exponentiation, add the following case to diff: ((^) (if (equals x u) (list * v (list ^ x (list  v 1))) (list * v (list * (list ^ u (list  v 1)) (diff x u))))) Here are the results: a. > (diff x (+ (^ x 2) (+ (* 2 x) 1))) (+ (* 2 (^ x ( 2 1))) (+ (+ (* 2 1) (* x 0)) 0)) b. > (diff x (/ ( (* 5 x) (* 2 y)) (+ (^ x 2) 1))) (/ ( (* (+ (^ x 2) 1) ( (+ (* 5 1) (* x 0)) (+ (* 2 0) (* y 0)))) (* ( (* 5 x) (* 2 y)) (+ (* 2 (^ x ( 2 1))) 0))) (* ( (* 5 x) (* 2 y)) (+ (^ x 2) 1)))
4 FUNCTIONAL PROGRAMMING The rules can be as extensive as desired; here will we consider only the two rules given as part of the problem, plus mutltiplfication by 0: a. x + 0 = 0 + x = x x 1 = 1 x = x x 0 = 0 x = 0 b. (define (simpl expr) (if (not (list? expr)) expr (let ((op (car expr)) (u ((simpl cadr expr))) (v ((simpl caddr expr)))) (case op ((+) (if (equal? u 0) v (if (equal? v 0) u (list + u v)))) ((*) (if (or (equal? u 0) (equal? v 0)) 0 (if (equal? u 1) v (if (equal? v 1) u (list * u v))))) (else (list op u v) )))) c. c1 + c2 = c3 where c3 = c1 + c2 c1 c2 = c4 where c4 = c1 c2 d. (define (constarith expr) (if (not (list? expr)) expr (let ((u (constarith (cadr expr))) (v (constarith (caddr expr)))) (if (or (not (number? u)) (not (number? v))) expr (case (car expr) ((+) (+ u v)) ((*) (* u v)) (else (list (car expr) u v)) ))))) e. (define (simplify expr) (let ((se (constarith (simpl expr)))) (if (equal? expr se) expr (simplify se) ))) a. No solution prints. b. The solution is: ( ) c. The solution is: ( ). Backtracking is required.
5 The Knights tour solution is in the file knight.scm in the ch14code directory The function try expects the initial knight position to be given, e.g.: (try ((3 3))) The board is kept in reverse order; the current position of the knight is at the front of the list. Each knight position is given as a list of row, column entries; in the example above, the knight is at row 3, column 3. A move is kept as an integer from 1 to the length of trial, which is a list of knight moves relative to its current position. This implementation required a slight modification to the function trywh Evaluate the following expressions using your Haskell interpreter: a. 3 b. Error: index (5) too large. c. 1 d. [2,3,4,5] a. [( Jane, ),( Bob, ),( Allen, ),( Bob, )] b. [( Allen, ),( Bob, )] deleteentry :: Person > Phonebook > Phonebook deleteentry p pb = [entry entry < pb, fst(entry) /= p] elements [] = 0 elements (x:xs) = 1 + elements(xs) The file Clite.hs in the ch14code directory is the skeleton of a Clite interpreter in Haskell. It contains the definitions in Section as well as the following function. m (Block b) state b == [] = state otherwise = m (Block (tail b)) (m (head b) state) The file Clite.hs in the ch14code directory is the skeleton of a Clite interpreter in Haskell (including int and bool values, but not char and float). It contains the following expansion of the eval function on page 403, along with a new apply function:
6 FUNCTIONAL PROGRAMMING eval :: Expression > State > Value eval (Var v) state = get v state eval (Lit v) state = v eval (Binary op e1 e2) state = apply op (eval e1 state) (eval e2 state) apply :: Op > Value > Value > Value apply "+" (Intval a) (Intval b) = (Intval (a + b)) apply "" (Intval a) (Intval b) = (Intval (a  b)) apply "*" (Intval a) (Intval b) = (Intval (a * b)) apply "/" (Intval a) (Intval b) = (Intval (a div b)) apply "<" (Intval a) (Intval b) = (Boolval (a < b)) apply "<=" (Intval a) (Intval b) = (Boolval (a <= b)) apply "==" (Intval a) (Intval b) = (Boolval (a == b)) apply "!=" (Intval a) (Intval b) = (Boolval (a /= b)) apply ">=" (Intval a) (Intval b) = (Boolval (a >= b)) apply ">" (Intval a) (Intval b) = (Boolval (a > b)) apply "&&" (Boolval a) (Boolval b) = (Boolval (a && b)) apply " " (Boolval a) (Boolval b) = (Boolval (a b)) The file Clite.hs in the ch14code directory contains the following expanded definition of Expression given on page 403, along with expanded definitions of eval and apply given above, and the new function applyunary: data Expression =... Unary Op Expression deriving (Eq, Ord, Show) eval (Unary op e) state = applyunary op (eval e state) applyunary :: Op > Value > Value applyunary "!" (Boolval a) = (Boolval (not a)) Here is a summary: Let s = [("x", (Intval 5)), ("y", (Intval 3)), ("z", (Intval 1))] Then eval (Binary "+" (Var "y") (Lit (Intval 2))) s = apply "+" (eval (Var "y") s) (eval (Lit (Intval 2)) s) = apply "+" (get "y" s) (eval (Lit (Intval 2)) s) = apply "+" (Intval 3) (Intval 2) = Intval 3+2 = Intval length [] = 0 length (w:ws) = 1 + length ws a. fibslow(25) delivers the result in about 20 seconds. fibslow(50) may still be running as you read this solution! The reason for this
7 69 performance is that fibslow(n) recalculates fibslow(k) twice for every value of k < n. (b) This recalculation is eliminated by fibfast, which computes each number in the sequence only once, and then picks the last number in the sequence at the end of this single chain of calls. Thus, fibfast(25) delivers the result immediately, and fibfast(50) delivers the result immediately See the file simplify.hs in the directory ch14code, which implements the answer given in Exercise 14.14a Two Haskell files that solve modest Sudoku puzzles are given in the ch14code directory. These programs assume that the Sudoku game board squares are numbered from left to right from 0 to 80. So row 0 = [0..9] and col 0 = [0,9,18,27,36,45,54,63,72]. Given that we can compute these, then the board values in row 0 are: [ board!!i i < row 0 ] Thus, we can use notelem to determine whether or not a trial move is safe. The basic strategy in these programs mimics that of the Eight Queens problem. Instead of backtracking, we keep a list of boards and each board has the same number of zeros (designating empty slots). Proceeding bottomup and using set theory, we first substitute for a single board bd and a single zero index z, all values from 1 to 9, replicating the entire board each time that the substituion is safe: replaceone z bd = [ replace z v bd bd!!z == 0, v < [1..9], v safe at position z ] Moving up a level, we substitute for position z for all boards b in the generated list bs. replaceall z bs = [ replaceone z b b < bs ] To solve for all zeros, we must use recursion: solve bs [ ] = bs solve bs z:zs = solve (replaceall z bs) zs Thus, a puzzle is solved by the function: sudoku bd = solve [bd] (zeros bd)
8 FUNCTIONAL PROGRAMMING There is only one remaining problem. The replaceall function generates an extra [ ], giving [[[Int]]] instead of the desired [[Int]]. Two possible solutions for this problem are: a. Combine replaceone and replaceall into one function. This is shown by the function add in the program sudoku1.hs b. Flatten the lists. This is shown in the program sudoku2.hs To solve a sample puzzle, load one of these programs into the Haskell interpreter and then make the call: sudoku easy1 at the prompt. To solve other puzzles than easy1, change the argument to this call Some of the abstract syntax for Clite is modeled in Haskell the file Clite.hs, which has solutions to Exercises Use Appendix A for a complete definition of the Clite type checking functions. The Clite type map can be modeled as follows: type Typemap = [(Variable, Type)] type Variable = String type Type = "int" "boolean" "char" "float" The function typing needs Haskell definitions of the abstract concepts of Declaration and Program, and can be defined as a function. All the validity functions can be defined using these definitions together with a complete Haskell recursive data type definition of Clite abstract syntax Most of this is summarized in Section , along with the file Clite.hs which has solutions to Exercises The challenge here is to complete the implementation of the Clite lnterpreter in Haskell and then demonstrate its completeness by interpreting a variety of abstract Clite programs. Use Appendix A for a complete definition of the Clite meaning functions This problem is reminiscent of a classical exercise in functional programming where students built a Scheme interpreter in Scheme. Usually a small subset of the Scheme function library was implemented, including functions cons, car, cdr, conditional expressions, and function definition and call. Fortunately, Scheme syntax is simple, and can be defined in just a few BNF rules. Tokens in Scheme are either parentheses, symbols, or numbers. Thus, the abstract syntax is also simple. Implementing the runtime semantics of Scheme in Java requires the design of a readevalprint loop. At each iteration, the user either calls or defines a Scheme function and
9 71 then the system evaluates (or stores) it and displays the result, returning to the user with a prompt to begin the next iteration. Dealing with Haskell syntax for this exercise is a bit more cumbersome, since the syntax is more complex. Moreover, the TokenStream class will be more difficult to implement due to a greater variety of operators and reserved words. If Haskell is chosen as the language for this exercise, we recommend that students limit their attention to a subset that has only a few arithmetic operators and the ability to define recursive functions on them. Anything more ambitious risks becoming tedious and unrewarding.
10 FUNCTIONAL PROGRAMMING
Project 2: Scheme Interpreter
Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same
More informationNormal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?
Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated
More informationScheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7
Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are firstclass values E.g., functions
More informationCSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGrawHill Companies, Inc.
CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:
More informationIntroduction to Functional Programming in Haskell 1 / 56
Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning Firstorder vs. higherorder
More informationA Brief Introduction to Scheme (II)
A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data
More informationBuilding a system for symbolic differentiation
Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)
More informationSCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015
SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationChapter 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 informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs Sexpressions cons, car, cdr Defining functions readevalprint loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationJim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4
Jim Lambers ENERGY 211 / CME 211 Autumn Quarter 200809 Programming Project 4 This project is due at 11:59pm on Friday, October 31. 1 Introduction In this project, you will do the following: 1. Implement
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More information(Func&onal (Programming (in (Scheme)))) Jianguo Lu
(Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you
More informationPROGRAMMING 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 informationScheme: Strings Scheme: I/O
Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of
More informationCS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College
CS5 Programming Languages Handout # 9 Prof. Lyn Turbak March, 00 Wellesley College Postfix: A Simple Stack Language Several exercises and examples in this course will involve the Postfix minilanguage.
More informationCSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona
1/43 CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg Functions over Lists
More informationCA4003 Compiler Construction Assignment Language Definition
CA4003 Compiler Construction Assignment Language Definition David Sinclair 20172018 1 Overview The language is not case sensitive. A nonterminal, X, is represented by enclosing it in angle brackets, e.g.
More informationCSC312 Principles of Programming Languages : Type System. Copyright 2006 The McGrawHill Companies, Inc.
CSC312 Principles of Programming Languages : Type System Ch. 6 Type System 6.1 Type System for Clite 6.2 Implicit Type Conversion 6.3 Formalizing the Clite Type System Type System Type? Type error? Type
More informationScheme Quick Reference
Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries
More informationLecture 2: List algorithms using recursion and list comprehensions
Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns
More informationFall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationPolymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy
0602552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 201617 School of Computer Science c Uday Reddy201617 Handout 6: Polymorphic Type Systems 1. Polymorphic
More informationSOFTWARE ARCHITECTURE 6. LISP
1 SOFTWARE ARCHITECTURE 6. LISP Tatsuya Hagino hagino@sfc.keio.ac.jp slides URL https://vu5.sfc.keio.ac.jp/sa/ 2 Compiler vs Interpreter Compiler Translate programs into machine languages Compilers are
More informationALISP interpreter in Awk
ALISP interpreter in Awk Roger Rohrbach 1592 Union St., #94 San Francisco, CA 94123 January 3, 1989 ABSTRACT This note describes a simple interpreter for the LISP programming language, written in awk.
More informationCompilers. Compiler Construction Tutorial The Frontend
Compilers Compiler Construction Tutorial The Frontend Salahaddin University College of Engineering Software Engineering Department 20112012 Amanj Sherwany http://www.amanj.me/wiki/doku.php?id=teaching:su:compilers
More informationPrinciples of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003
Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in
More informationScheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.
Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu
More informationDefining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1
Defining Program Syntax Chapter Two Modern Programming Languages, 2nd ed. 1 Syntax And Semantics Programming language syntax: how programs look, their form and structure Syntax is defined using a kind
More informationB The SLLGEN Parsing System
B The SLLGEN Parsing System Programs are just strings of characters. In order to process a program, we need to group these characters into meaningful units. This grouping is usually divided into two stages:
More informationLecture 4 Abstract syntax
Lecture 4 Abstract syntax Abstract syntax examples for various languages: A simple expression language OCaml MiniJava (a subset of Java) CS 421 Class 4, 1/26/12 1 Ex: Abstract syntax of simple expressions
More informationGraphs. Directed graphs. Readings: Section 28
Graphs Readings: Section 28 CS 135 Winter 2018 12: Graphs 1 Directed graphs A directed graph consists of a collection of vertices (also called nodes) together with a collection of edges. An edge is an
More informationA tour of the Haskell Prelude
A tour of the Haskell Prelude Bernie Pope 2001 1 Haskell The Haskell language was conceived during a meeting held at the 1987 Functional Programming and Computer Architecture conference (FPCA 87). At the
More informationOrganization of Programming Languages CS3200/5200N. Lecture 11
Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages
More informationConsider the following EBNF definition of a small language:
xercise 1: Consider the following BNF definition of a small language: program ::= + decl ::= vardecl ::= "var" ":" "=" ";" procdecl ::= "procedure"
More informationFunctional Programming in Haskell Part I : Basics
Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian
More informationThe Warhol Language Reference Manual
The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming
More informationFunctional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda
Functional abstraction Readings: HtDP, sections 1924. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered
More informationThe Decaf Language. 1 Lexical considerations
The Decaf Language In this course, we will write a compiler for a simple objectoriented programming language called Decaf. Decaf is a stronglytyped, objectoriented language with support for inheritance
More informationTopic 5: Higher Order Functions
Topic 5: Higher Order Functions 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 10.10,
More informationShell CSCE 314 TAMU. Functions continued
1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in
More information;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for
Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy
More informationSyntax Intro and Overview. Syntax
Syntax Intro and Overview CS331 Syntax Syntax defines what is grammatically valid in a programming language Set of grammatical rules E.g. in English, a sentence cannot begin with a period Must be formal
More informationPractical Questions CSCA48 Week 6
Practical Questions CSCA48 Week 6 Trace the following functions with a variety of input, and describe their functionality in a single sentence. 1. def mystery(n): if n == 4: result = n result = 2 * mystery(n+1)
More informationMIDTERM EXAMINATION  CS130  Spring 2005
MIDTERM EAMINATION  CS130  Spring 2005 Your full name: Your UCSD ID number: This exam is closed book and closed notes Total number of points in this exam: 231 + 25 extra credit This exam counts for 25%
More informationASTs, 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 informationLSystem Fractal Generator: Language Reference Manual
LSystem Fractal Generator: Language Reference Manual Michael Eng, Jervis Muindi, Timothy Sun Contents 1 Program Definition 3 2 Lexical Conventions 3 2.1 Comments...............................................
More informationAn Introduction to Scheme
An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification
More informationCOP4020 Programming Languages. Syntax Prof. Robert van Engelen
COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview Tokens and regular expressions Syntax and contextfree grammars Grammar derivations More about parse trees Topdown and bottomup
More informationFunctions and Recursion. Dr. Philip Cannata 1
Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 2 let transformation,
More informationTree Oriented Programming. Jeroen Fokker
Tree Oriented Programming Jeroen Fokker Tree oriented programming Many problems are like: Input text transform process unparse Output text Tree oriented programming Many problems are like: Input text parse
More informationLecture 3 Tao Wang 1
Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers
More informationPrinciples of Programming Languages COMP251: Syntax and Grammars
Principles of Programming Languages COMP251: Syntax and Grammars Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2007
More informationHow to Design Programs Languages
How to Design Programs Languages Version 4.1 August 12, 2008 The languages documented in this manual are provided by DrScheme to be used with the How to Design Programs book. 1 Contents 1 Beginning Student
More informationDecaf Language Reference
Decaf Language Reference Mike Lam, James Madison University Fall 2016 1 Introduction Decaf is an imperative language similar to Java or C, but is greatly simplified compared to those languages. It will
More informationProgramming 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 informationCSCI 3155: Principles of Programming Languages Exam preparation #1 2007
CSCI 3155: Principles of Programming Languages Exam preparation #1 2007 Exercise 1. Consider the ifthenelse construct of Pascal, as in the following example: IF 1 = 2 THEN PRINT X ELSE PRINT Y (a) Assume
More information7. Introduction to Denotational Semantics. Oscar Nierstrasz
7. Introduction to Denotational Semantics Oscar Nierstrasz Roadmap > Syntax and Semantics > Semantics of Expressions > Semantics of Assignment > Other Issues References > D. A. Schmidt, Denotational Semantics,
More informationData Types The ML Type System
7 Data Types 7.2.4 The ML Type System The following is an ML version of the tailrecursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let
More informationCSCE 314 Programming Languages
CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee 1 Contents 1. Historical Background of Haskell 2. Lazy, Pure, and Functional Language 3. Using ghc and ghci 4. Functions 5. Haskell Scripts
More informationWriting Evaluators MIF08. Laure Gonnord
Writing Evaluators MIF08 Laure Gonnord Laure.Gonnord@univlyon1.fr Evaluators, what for? Outline 1 Evaluators, what for? 2 Implementation Laure Gonnord (Lyon1/FST) Writing Evaluators 2 / 21 Evaluators,
More informationMore Programming Constructs  Introduction
More Programming Constructs  Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and
More informationARG! Language Reference Manual
ARG! Language Reference Manual Ryan Eagan, Mike Goldin, River Keefer, Shivangi Saxena 1. Introduction ARG is a language to be used to make programming a less frustrating experience. It is similar to C
More informationChapter 3 Lexical Analysis
Chapter 3 Lexical Analysis Outline Role of lexical analyzer Specification of tokens Recognition of tokens Lexical analyzer generator Finite automata Design of lexical analyzer generator The role of lexical
More informationexample: name1=jan name2=mike export name1 In this example, name1 is an environmental variable while name2 is a local variable.
Bourne Shell Programming Variables  creating and assigning variables Bourne shell use the set and unset to create and assign values to variables or typing the variable name, an equal sign and the value
More informationSpecification of FlatZinc. Nicholas Nethercote Version 0.8.1
Specification of FlatZinc Nicholas Nethercote Version 0.8.1 1 Contents 1 Introduction 3 2 Overview of a Model 3 2.1 Specifying a Problem........................... 3 2.2 Evaluation of a Model Instance.....................
More informationA Sudoku Solver Pruning (3A)
A Sudoku Solver Pruning (3A) Richard Bird Implementation Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation
More informationGAWK Language Reference Manual
GAWK Language Reference Manual Albert Cui, Karen Nan, MeiVern Then, & Michael Raimi So good, you re gonna GAWK. 1.0 Introduction This manual describes the GAWK language and is meant to be used as a reliable
More informationFundamentals of Compilation
PART ONE Fundamentals of Compilation 1 Introduction A compiler was originally a program that compiled subroutines [a linkloader]. When in 1954 the combination algebraic compiler came into use, or rather
More informationAbstract Interpretation
Abstract Interpretation Ranjit Jhala, UC San Diego April 22, 2013 Fundamental Challenge of Program Analysis How to infer (loop) invariants? Fundamental Challenge of Program Analysis Key issue for any analysis
More informationAnnouncement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.
Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also
More informationCompiler course. Chapter 3 Lexical Analysis
Compiler course Chapter 3 Lexical Analysis 1 A. A. Pourhaji Kazem, Spring 2009 Outline Role of lexical analyzer Specification of tokens Recognition of tokens Lexical analyzer generator Finite automata
More informationPattern Matching for Scheme
Pattern Matching for Scheme Andrew K. Wright March 1996 Department of Computer Science MS 132 Rice University 6100 Main Street Houston, Texas 770051892 Contents 1 Match 1 1.1 Definition... 1 1.1.1 Patterns...
More informationSyntax Analysis/Parsing. Contextfree grammars (CFG s) Contextfree grammars vs. Regular Expressions. BNF description of PL/0 syntax
Susan Eggers 1 CSE 401 Syntax Analysis/Parsing Contextfree grammars (CFG s) Purpose: determine if tokens have the right form for the language (right syntactic structure) stream of tokens abstract syntax
More information(Not Quite) Minijava
(Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier
More informationK Reference Card. Complete example
K Reference Card Complete example package examples.example1 annotation doc : String class Date class Person { name : String age : Int ssnr : Int @doc("employee inherits from Person") class Employee extends
More information1. In C++, reserved words are the same as predefined identifiers. a. True
C++ Programming From Problem Analysis to Program Design 8th Edition Malik TEST BANK Full clear download (no formatting errors) at: https://testbankreal.com/download/cprogrammingproblemanalysisprogramdesign8theditionmaliktestbank/
More informationCS 360: Programming Languages Lecture 12: More Haskell
CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due
More informationWriting code that I'm not smart enough to write. A funny thing happened at Lambda Jam
Writing code that I'm not smart enough to write A funny thing happened at Lambda Jam Background "Let s make a lambda calculator" Rúnar Bjarnason Task: write an interpreter for the lambda calculus Lambda
More informationVectors in Scheme. Data Structures in Scheme
Data Structures in Scheme Vectors in Scheme In Scheme, lists and Sexpressions are basic. Arrays can be simulated using lists, but access to elements deep in the list can be slow (since a list is a linked
More informationChapter 3: Lexing and Parsing
Chapter 3: Lexing and Parsing Aarne Ranta Slides for the book Implementing Programming Languages. An Introduction to Compilers and Interpreters, College Publications, 2012. Lexing and Parsing* Deeper understanding
More informationName of Allah, Most Gracious, Most Merciful
Name of Allah, Most Gracious, Most Merciful EMail: Hossein Fereidooni It was the best motivation for writing this article. 1 Hossein Fereidooni Solving Sudoku Using Informed Search Algorithms 2 Introduction
More informationProgramming Paradigms, Fall 06
Programming Paradigms, Fall 06 Multiple Choice Exam January 29, 2007, 10:00 11:15 ID Name Each of the following questions has exactly one correct answer. For each question, you may select one or more answers
More informationTwister: Language Reference Manual
Twister: Language Reference Manual Manager: Anand Sundaram (as5209) Language Guru: Arushi Gupta (ag3309) System Architect: Annalise Mariottini (aim2120) Tester: Chuan Tian (ct2698) February 23, 2017 Contents
More informationImplementation of a Sudoku Solver Using Reduction to SAT
Implementation of a Sudoku Solver Using Reduction to SAT For this project you will develop a Sudoku solver that receives an input puzzle and computes a solution, if one exists. Your solver will: read an
More informationThe Decaf language 1
The Decaf language 1 In this course, we will write a compiler for a simple objectoriented programming language called Decaf. Decaf is a stronglytyped, objectoriented language with support for inheritance
More informationCommon LISPIntroduction
Common LISPIntroduction 1. The primary data structure in LISP is called the sexpression (symbolic expression). There are two basic types of sexpressions: atoms and lists. 2. The LISP language is normally
More informationSemantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known.
SEMANTIC ANALYSIS: Semantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known. Parsing only verifies that the program consists of tokens
More informationMandatory Exercise 1 INF3110
Mandatory Exercise 1 INF3110 In this exercise, you are going to write a small interpreter for a simple language for controlling a robot on a 2dimensional grid. The language is called ROBOL, a clever acronym
More informationCSCIGA Final Exam
CSCIGA 2110003  Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly
More informationCompiler Code Generation COMP360
Compiler Code Generation COMP360 Students who acquire large debts putting themselves through school are unlikely to think about changing society. When you trap people in a system of debt, they can t afford
More informationCSCI 3155: Lab Assignment 2
CSCI 3155: Lab Assignment 2 Fall 2017 Checkpoint due Friday, September 15, 2017 Assignment due Friday, September 22, 2017 Learning Goals. The primary learning goals of this lab are to understand the following:
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exectime Dynamic Values (Semantics) Compiletime Static Types 1. Programmer enters expression 2. ML checks if expression is welltyped Using a precise set of
More informationPRACTICAL CLASS: Flex & Bison
Master s Degree Course in Computer Engineering Formal Languages FORMAL LANGUAGES AND COMPILERS PRACTICAL CLASS: Flex & Bison Eliana Bove eliana.bove@poliba.it Install On Linux: install with the package
More informationFunctional Paradigm II
Processadors de Llenguatge II Functional Paradigm II Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra UserDefined Types How to define the new type.
More information6.001, Spring Semester, 1998, Final Exam Your Name: 2 Question 1 (12 points): Each of the parts below should be treated as independent. For each part,
1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Spring Semester, 1998, Final Exam Your Name: Open
More informationChapter 2 The Language PCF
Chapter 2 The Language PCF We will illustrate the various styles of semantics of programming languages with an example: the language PCF Programming language for computable functions, also called MiniML.
More informationSyntaxDirected Translation. Introduction
SyntaxDirected Translation Introduction Translation of languages guided by contextfree grammars Attach attributes to the grammar symbols Values of the attributes are computed by semantic rules associated
More informationType Conversion. and. Statements
and Statements Type conversion changing a value from one type to another Void Integral Floating Point Derived Boolean Character Integer Real Imaginary Complex no fractional part fractional part 2 tj Suppose
More informationLesson 4A overview. Introduction to Map Algebra (4A) Map Algebra functions (4B)
Map Algebra Lesson 4A overview Introduction to Map Algebra (4A) Language components Syntax and rules Objects Operators Commands Exercise 5A Map Algebra functions (4B) Function syntax Local functions Focal
More information