Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Similar documents
CSc 520. Principles of Programming Languages 11: Haskell Basics

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

Programming Paradigms

CSc 372. Comparative Programming Languages. 15 : Haskell List Comprehension. Department of Computer Science University of Arizona

CSc 372 Comparative Programming Languages

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Haskell through HUGS THE BASICS

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

CSc 520 Principles of Programming Languages

CSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona

CSc 372. Comparative Programming Languages. 3 : Haskell Introduction. Department of Computer Science University of Arizona

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

CSc 520 Principles of Programming Languages

An introduction introduction to functional functional programming programming using usin Haskell

CS 11 Haskell track: lecture 1

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

CSc 372. Comparative Programming Languages. 13 : Haskell Lazy Evaluation. Department of Computer Science University of Arizona

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

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

Shell CSCE 314 TAMU. Haskell Functions

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

CS 320: Concepts of Programming Languages

A quick introduction to SML

Functional Programming Languages (FPL)

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Functional Programming. Big Picture. Design of Programming Languages

CSc 520 Principles of Programming Languages. 26 : Control Structures Introduction

Functional Programming in Haskell Part I : Basics

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus

CS 4110 Programming Languages & Logics. Lecture 17 Programming in the λ-calculus

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Lecture 19: Functions, Types and Data Structures in Haskell

COMP 410 Lecture 1. Kyle Dewey

SMURF Language Reference Manual Serial MUsic Represented as Functions

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CMSC 330: Organization of Programming Languages. Operational Semantics

CSE 3302 Programming Languages Lecture 8: Functional Programming

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg

Basic concepts. Chapter Toplevel loop

Haskell Overview II (2A) Young Won Lim 9/26/16

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Haskell Refresher Informatics 2D

CS52 - Assignment 8. Due Friday 4/15 at 5:00pm.

Chapter 11 :: Functional Languages

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions

Lecture 3: Recursion; Structural Induction

Outline. What is semantics? Denotational semantics. Semantics of naming. What is semantics? 2 / 21

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

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

Handout 2 August 25, 2008

An Explicit-Continuation Metacircular Evaluator

Programming Paradigms

CSc 372 Comparative Programming Languages

Haskell-Tutorial. Damir Medak Gerhard Navratil. Institute for Geoinformation Technical University Vienna. February 2003

CSc 372. Comparative Programming Languages. 1 : Introduction. Department of Computer Science University of Arizona

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

Lambda Calculus. Variables and Functions. cs3723 1

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1

To figure this out we need a more precise understanding of how ML works

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

CS 440: Programming Languages and Translators, Spring 2019 Mon

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

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

Standard ML. Curried Functions. ML Curried Functions.1

Logic - CM0845 Introduction to Haskell

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

JVM ByteCode Interpreter

2.8. Decision Making: Equality and Relational Operators

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

Denotational Semantics. Domain Theory

COMP80 Lambda Calculus Programming Languages Slides Courtesy of Prof. Sam Guyer Tufts University Computer Science History Big ideas Examples:

Chapter 15. Functional Programming Languages

Types, Expressions, and States

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Dan Grossman Fall 2011

Introduction to the λ-calculus

Programming Language Concepts: Lecture 14

Formal semantics of loosely typed languages. Joep Verkoelen Vincent Driessen

Programming Languages Third Edition

Course Overview. Arrays. Static Arrays. Static Arrays. Static Arrays with different lower bound. Static Arrays. PART I: overview material

Fall Lecture 3 September 4. Stephen Brookes

CPS 506 Comparative Programming Languages. Programming Language Paradigm

Programming with Math and Logic

Fall 2018 Lecture 1

Lecture 2: Big-Step Semantics

Project 1: Scheme Pretty-Printer

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Chapter 3 (part 3) Describing Syntax and Semantics

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

INTRODUCTION TO FUNCTIONAL PROGRAMMING

Transcription:

Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language we have basically two techniques to choose from when defining a new function: Recursion 2 Composition Recursion is often used for basic low-level functions, such that might be defined in a function library. Composition (which we will cover later) is used to combine such basic functions into more powerful ones. Recursion is closely related to proof by induction. Copyright c 2 Christian Collberg Defining Functions... Defining Functions... Here s the ubiquitous factorial function: fact :: Int -> Int fact n = n n fact (n-) The first part of a function definition is the type signature, which gives the domain and range of the function: fact :: Int -> Int The second part of the definition is the function declaration, the implementation of the function: fact n = n The syntax of a type signature is fun name :: argument types fact takes one integer input argument and returns one integer result. The syntax of function declarations: fun name param names = fun body

Conditional Expressions Conditional Expressions... e e2 e3 is a conditional expression that returns the value of e2 e evaluates to True. If e evaluates to, the value of e3 is returned. Examples: True 5 6 5 5 6 6 2 5 6 6 5 + 3 2 8 Note that this is dferent from Java s or C s -statement, but just like their ternary operator?:: int max = (x>y)?x:y; Example: abs :: Int -> Int abs n = n> n -n sign :: Int -> Int sign n = n< - n Unlike in C and Java, you can t leave off the -part! Guarded Equations Defining Functions... An alternative way to define conditional execution is to use guards: abs :: Int -> Int abs n n>= = n otherwise = -n sign :: Int -> Int sign n n< = - n = otherwise = The pipe symbol is read such that. otherwise is defined to be True. Guards are often easier to read it s also easier to very that you have covered all cases. fact is defined recursively, i.e. the function body contains an application of the function itself. The syntax of function application is: fun name arg. This syntax is known as juxtaposition. We will discuss multi-argument functions later. For now, this is what a multi-argument function application ( call ) looks like: fun name arg arg 2 arg n Function application examples: fact fact 5 2 fact (3+2) 2

Multi-Argument Functions The error Function A simple way (but usually not the right way) of defining an multi-argument function is to use tuples: add :: (Int,Int) -> Int add (x,y) = x+y > add (4,2) 42 Later, we ll learn about Curried Functions. error string can be used to generate an error message and terminate a computation. This is similar to Java s exception mechanism, but a lot less advanced. f :: Int -> Int f n = n< error "illegal argument" n <= n f (n-) > f (-) Program error: illegal argument Layout Function Application A function definition is finished by the first line not indented more than the start of the definition myfunc :: Int -> Int myfunc x = x 99 myfunc :: Int -> Int myfunc x = x 99 myfunc :: Int -> Int myfunc x = x 99 The last two generate a Syntax error in expression when the function is loaded. Function application ( calling a function with a particular argument ) has higher priority than any other operator. In math (and Java) we use parentheses to include arguments; in Haskell no parentheses are needed. > f a + b means > (f a) + b since function application binds harder than plus.

Function Application... Here s a comparison between mathematical notations and Haskell: Math Haskell f (x) f x f (x,y) f x y f (g(x)) f (g x) f (x,g(y)) f x (g y) f (x)g(y) f x g y Recursive Functions Simple Recursive Functions Simulating Recursive Functions Typically, a recursive function definition consists of a guard (a boolean expression), a base case (evaluated when the guard is True), and a general case (evaluated when the guard is ). fact n = n guard base case n fact (n-) general case We can visualize the evaluation of using a tree view, box view, or reduction view. The tree and box views emphasize the flow-of-control from one level of recursion to the next The reduction view emphasizes the substitution steps that the hugs interpreter goes through when evaluating a function. In our notation boxed subexpressions are substituted or evaluated in the next reduction. Note that the Haskell interpreter may not go through exactly the same steps as shown in our simulations. More about this later.

Tree View of Tree View of 32=6 3 3 fact (3) 2 2 fact (2) fact fact () fact This is a Tree View of. We keep going deeper into the recursion (evaluating the general case) until the guard is evaluated to True. 3 3 fact (3) 2=2 2 2 fact (2) fact = fact () fact When the guard is True we evaluate the base case and return back up through the layers of recursion....... Box View of Box View of... 3 3 2 2 fact

Box View of... Reduction View of 3 2 fact 3 3 fact (3-) 3 fact (3-) 3 fact (3-) 3 3 2 2 fact (2-) 3 2 fact (2-) 3 (2 fact (2-)) 3 (2 fact ) 3 (2 fact (-)) Reduction View of... Recursion Over Lists 3 (2 fact (-)) 3 (2 fact (-)) 3 (2 ( fact (-))) 3 (2 ( fact )) 3 (2 ( fact (-))) 3 (2 ( True fact (-))) 3 (2 ( )) 3 (2 ) 3 2 6 In the fact function the guard was n, and the recursive step was fact(n-). I.e. we subtracted from fact s argument to make a simpler (smaller) recursive case. We can do something similar to recurse over a list: The guard will often be n[ ] (other tests are of course possible). 2 To get a smaller list to recurse over, we often split the list into its head and tail, head:tail. 3 The recursive function application will often be on the tail, f tail.

The length Function Reduction View of len [5,6] In English: The length of the empty list [ ] is zero. The length of a non-empty list S is one plus the length of the tail of S. In Haskell: len :: [Int] -> Int len s = s [ ] + len (tail s) We first check we ve reached the end of the list s[ ]. Otherwise we compute the length of the tail of s, and add one to get the length of s itself. len s = s [ ] + len (tail s) len [5,6] [5,6][ ] + len (tail [5,6]) + len (tail [5,6]) + len [6] + ( [6][ ] + len (tail [6])) + ( + len (tail [6])) + ( + len [ ]) + ( + ( [ ][ ] +len (tail [ ]))) + ( + )) + 2 Tree View of len [5,6,7] len [5,6,7] [5,6,7][] + len (tail [5,6,7]) len [6,7] len [7] len [] +2=3 [6,7][] + len (tail [6,7]) += [7][] + len (tail [7]) [][]... +=2 len :: [Int] -> Int len s = s[ ] +len(tail s) Tree View of len [5,6,7]