Reminder About Functions

Slides:



Advertisements
Similar presentations
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Advertisements

Chapter 5: Abstraction, parameterization, and qualification Xinming (Simon) Ou CIS 505: Programming Languages Kansas State University Fall
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Procedures and Control Flow CS351 – Programming Paradigms.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Programming with Recursion
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 10 Function Implementation In theory, there.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Chapter 10 Implementing Subprograms. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Semantics of Call and Return The subprogram call and return.
CSC321: Programming Languages1 Programming Languages Tucker and Noonan Chapter 9: Functions 9.1 Basic Terminology 9.2 Function Call and Return 9.3 Parameters.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 9 Functions It is better to have 100 functions.
Recursion CS Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine.
Dr. Philip Cannata 1 with ReL. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython in Java This.
Dr. Philip Cannata 1 fJyswan. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython in Java This.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Dr. Philip Cannata 1 Functions and Recursion. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Copyright © 2006 The McGraw-Hill Companies, Inc. Basic Terminology Value-returning functions: –known as “non-void functions/methods” in C/C++/Java –called.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
Today’s lecture Review chapter 5 go over exercises.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Dr. Philip Cannata 1 Functions and Recursion Programming Languages.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Dr. Philip Cannata 1 Names, Types, and Functions standard hue names.
Defining Your Own Classes II
CS314 – Section 5 Recitation 9
C11, Implications of Inheritance
Functions.
Lecture 2 Python Basics.
Introduction to Python
Lecture 2: Data Types, Variables, Operators, and Expressions
Chapter 6 Functions.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
PLAI Types Chapters 24 – 30 Types, Type Judgments, Type Systems and Type Safety - Chapters Type Inference – Chapter 30.
Is everyone signed up on piazza?
Default Argument.
Procedures – Overview Lecture 19 Mon, Mar 28, 2005.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Chapter 4 Writing Classes.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Recap Week 2 and 3.
Stacks.
What would be our focus ? Geometry deals with Declarative or “What is” knowledge. Computer Science deals with Imperative or “How to” knowledge 2/23/2019.
Announcements Quiz 5 HW6 due October 23
Yan Shi CS/SE 2630 Lecture Notes
Names, Types, and Functions
Variables, Data Types & Math
Main() { int fact; fact = Factorial(4); } main fact.
Programming Languages
topics interpreters meta-linguistic abstraction eval and apply
Unit-1 Introduction to Java
CISC101 Reminders Assignment 3 due today.
def-ining a function A function as an execution control structure
Functions John R. Woodward.
Presentation transcript:

Reminder About Functions (let ((z 17)) (let ((z 3) (a 5) (x (lambda (x y) (- x (+ y z))))) (let ((z 50) (a 5)) (x z a)))) int h, i; void B(int w) { int j, k; i = 2*w; w = w+1; } void A(int x, int y) { bool i, j; B(h); int main() { int a, b; h = 5; a = 3; b = 2; A(a, b); parameters and local variables Return address Saved registers Temporary variables Return value

Hmm Runtime Stack for Factorial 3 Calling function: factorial BasePtr = 3, printing runtime stack null: null n: 3 answer: null number: 3 BasePtr = 5, printing runtime stack n: 2 BasePtr = 7, printing runtime stack n: 1 BasePtr = 9, printing runtime stack n: 0 int factorial(int n) { if(n < 1) { return 1; } else { return n * factorial(n - 1); int main() { int number, answer; number = 3; answer = factorial(number); print(answer); Exiting function: factorial BasePtr = 9, printing runtime stack null: null n: 0 return#factorial: 1 n: 1 n: 2 n: 3 answer: null number: 3 BasePtr = 7, printing runtime stack BasePtr = 5, printing runtime stack return#factorial: 2 BasePtr = 3, printing runtime stack return#factorial: 6

A Taxonomy of Functions first-order Functions are not values in the language. They can only be defined in a designated portion of the program, where they must be given names for use in the remainder of the program. The functions in F1WAE are of this nature, which explains the 1 in the name of the language. higher-order Functions can [be defined anywhere in a program and] return other functions as values. first-class Functions are values with all the rights of other values. In particular, they can be supplied as the value of arguments to functions, returned by functions as answers, and stored in data structures. [They can also be defined anywhere in a program.]

Functions in Python/Jython http://www.penzilla.net/tutorials/python/functions/ Python and Functions: Python is a little different from other languages like C/C++ and Java, in that functions are not magic constructs, but values. Yes, functions in Python, are like integers in C. They are simply values and can be passed to other functions/object constructors, and so forth. We've already seen a pretty simple example of a Python function in the form of the venerable "Hello World!" program. Let's take another look at it: # hello.py def hello(): print "Hello World!“ return

Functions in Python/Jython $ cat cs345.py x=3+4 def h ():    print 'Hello' h h() print (lambda x, y : x + y)(2, 3) $ dist/bin/jython cs345.py MyPrint: MyPrint: Hello 5 $ dist/bin/jython ast/astview.py cs345.py MyPrint: MyPrint: ('Module',  ('body',   ('Assign (1,0)',    ('targets', ('Name (1,0)', ('id', 'x'), ('ctx', ('Store',)))),    ('value',     ('BinOp (1,2)',      ('left', ('Num (1,2)', ('n', 3))),      ('op', ('Add',)),      ('right', ('Num (1,4)', ('n', 4)))))),   ('FunctionDef (2,0)',    ('name', 'h'),    ('args',     ('arguments',      ('args',),      ('vararg', None),      ('kwarg', None),      ('defaults',))),    ('body',     ('Print (3,3)',      ('dest', None),      ('values', ('Str (3,9)', ('s', 'Hello'))),      ('nl', True))),    ('decorator_list',)),   ('Expr (4,0)', ('value', ('Name (4,0)', ('id', 'h'), ('ctx', ('Load',))))),   ('Expr (5,0)',    ('value',     ('Call (5,0)',      ('func', ('Name (5,0)', ('id', 'h'), ('ctx', ('Load',)))),      ('args',),      ('keywords',),      ('starargs', None),      ('kwargs', None)))), ('Print (6,0)',    ('dest', None),    ('values',     ('Call (6,6)',      ('func',       ('Lambda (6,7)',        ('args',         ('arguments',          ('args',           ('Name (6,14)', ('id', 'x'), ('ctx', ('Param',))),           ('Name (6,17)', ('id', 'y'), ('ctx', ('Param',)))),          ('vararg', None),          ('kwarg', None),          ('defaults',))),        ('body',         ('BinOp (6,21)',          ('left', ('Name (6,21)', ('id', 'x'), ('ctx', ('Load',)))),          ('op', ('Add',)),          ('right', ('Name (6,25)', ('id', 'y'), ('ctx', ('Load',)))))))),      ('args', ('Num (6,28)', ('n', 2)), ('Num (6,31)', ('n', 3))),      ('keywords',),      ('starargs', None),      ('kwargs', None))),    ('nl', True)))) AST

"let" Can Be Made Redundant In the textbook, the author says the following: Now that we have functions and function invocation as two distinct primitives, we can combine them to recover the behavior of "with" as a special case. Every time we encounter an expression of the form {with {var named} body} we can replace it with {{fun {var} body} named} Example: In DrRacket: > (calc (parse '{with {x {+ 5 5}} {with {y {- x 3}} {+ y y}}}) ) 14 In jython: >>> (lambda x : (lambda y : y + y) (x - 3) ) (5 + 5) 14

"let" Can Be Made Redundant DrRacket (see Textbook, Chapter 3) v. Let in jython as in Homework #6 Welcome to DrRacket, version 5.0.2 [3m]. Language: plai; memory limit: 128 MB. > (calc (parse '{with {x {+ 5 5}} {+ x x}}) ) 20 > (calc (parse '{with {x 5} {+ x x}}) ) 10 > (calc (parse '{with {x {+ 5 5}} {with {y {- x 3}} {+ y y}}}) ) 14 > (calc (parse '{with {x 5} {+ x {with {x 3} x}}}) ) 8 > (calc (parse '{with {x 5} {+ x {with {x 3} 10}}}) ) 15 > (calc (parse '{with {x 5} {+ x {with {y 3} x}}}) ) 10 > (calc (parse '{with {x 5} {with {y x} y}}) ) 5 > (calc (parse '{with {x 5} {with {x x} x}}) ) 5 $ dist/bin/jython Jython 2.5.2rc4 (trunk, Feb 27 2011, 21:35:17) >>> (let x: 5+5: x+x)() 20 >>> (let x: 5: x+x)() 10 >>> (let x: 5+5:(let y: x-3: y+y)())() 14 >>> (let x: 5: x + (let x: 3: x)())() 8 >>> (let x: 5: x + (let x: 3: 10)())() 15 >>> (let x: 5: x + (let y: 3: x)())() 10 >>> (let x: 5: (let y: x: y)())() 5 >>> (let x: 5: (let x: x: x)())() 5