Shell CSCE 314 TAMU. Haskell Functions

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

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Shell CSCE 314 TAMU. Functions continued

An introduction introduction to functional functional programming programming using usin Haskell

Lecture 19: Functions, Types and Data Structures in Haskell

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

Shell CSCE 314 TAMU. Higher Order Functions

INTRODUCTION TO FUNCTIONAL PROGRAMMING

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CS 457/557: Functional Languages

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

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

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

CSCE 314 Programming Languages

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

A general introduction to Functional Programming using Haskell

CS 320: Concepts of Programming Languages

CSCE 314 Programming Languages

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

Imperative languages

Introduction. chapter Functions

Functional Programming in Haskell for A level teachers

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

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

Haskell Overview II (2A) Young Won Lim 8/23/16

Functional Programming

CSc 372 Comparative Programming Languages

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

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

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

11/6/17. Outline. FP Foundations, Scheme. Imperative Languages. Functional Programming. Mathematical Foundations. Mathematical Foundations

CMSC 330: Organization of Programming Languages. Operational Semantics

Putting the fun in functional programming

Lists. Michael P. Fourman. February 2, 2010

CS 320: Concepts of Programming Languages

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

Functional Programming in Haskell Part I : Basics

CSCE 314 Programming Languages. Interactive Programming: I/O

Chapter 11 :: Functional Languages

CS 440: Programming Languages and Translators, Spring 2019 Mon

Functional Programming. Pure Functional Programming

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

LECTURE 16. Functional Programming

CS 11 Haskell track: lecture 1

CSCE 314 Programming Languages

1.3. Conditional expressions To express case distinctions like

SML A F unctional Functional Language Language Lecture 19

Programming Languages Third Edition

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

Organization of Programming Languages CS3200/5200N. Lecture 11

Higher Order Functions in Haskell

Programming Languages

Last class. CS Principles of Programming Languages. Introduction. Outline

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

List Functions, and Higher-Order Functions

Box-and-arrow Diagrams

3. Functional Programming. Oscar Nierstrasz

Graphical Untyped Lambda Calculus Interactive Interpreter

Functional programming with Common Lisp

Functional Logic Programming Language Curry

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CSCE 314 Programming Languages

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Functional Programming. Big Picture. Design of Programming Languages

Functional Languages. Hwansoo Han

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

6.001 Notes: Section 8.1

Programming Paradigms

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CSCE 314 Programming Languages. Functional Parsers

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

CS 320 Midterm Exam. Fall 2018

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

Functional Programming Languages (FPL)

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

Typed Racket: Racket with Static Types

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

CS 360: Programming Languages Lecture 12: More Haskell

CPS 506 Comparative Programming Languages. Programming Language Paradigm

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Structure of Programming Languages Lecture 5

Which of the following expressions has the type int list?

INTRODUCTION TO HASKELL

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

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

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

COP4020 Programming Assignment 1 - Spring 2011

SOFTWARE ENGINEERING DESIGN I

CSCE 314 Programming Languages. Type System

Haskell through HUGS THE BASICS

Chapter 15. Functional Programming Languages

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

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Functional Programming. Overview. Topics. Recall λ-terms. Examples

Programming Language Pragmatics

String Computation Program

Transcription:

1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions

2 Outline Defining Functions List Comprehensions Recursion

3 Conditional Expressions As in most programming languages, functions can be defined using conditional expressions: if cond then e1 else e2 e1 and e2 must be of the same type else branch is always present

4 Guarded Equations As an alternative to conditionals, functions can also be defined using guarded equations. Prelude: Guarded equations can be used to make definitions involving multiple conditions easier to read: compare with

5 Guarded Equations (Cont.) Guards and patterns can be freely mixed, the first equation whose pattern matches and guard is satisfied is chosen.

6 Pattern Matching Many functions are defined using pattern matching on their arguments. not maps False to True, and True to False. Pattern can be a constant value, or include one or more variables.

Functions can be defined in many different ways using pattern matching. For example can be defined more compactly by However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: The underscore symbol _ is a wildcard pattern that matches any argument value. 7

8 Patterns are matched in order. For example, the following definition always returns False: Patterns may not repeat variables. For example, the following definition gives an error:

9 List Patterns Internally, every non-empty list is constructed by repeated use of an operator (:) called cons that adds an element to the start of a list. Means. Functions on lists can be defined using x:xs patterns. head and tail map any non-empty list to its first and remaining elements. is this definition complete?

10 Note: x:xs patterns only match non-empty lists: Shell CSCE 314 TAMU x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error: Patterns can contain arbitrarily deep structure:

11 Totality of Functions (Total) function maps every element in the function s domain to an element in its codomain. Partial function maps zero or more elements in the function s domain to an element in its codomain, and can leave some elements undefined. Haskell functions can be partial. For example:

12 Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. λ This nameless function takes a number x and returns the result x+x. The symbol λ is the Greek letter lambda, and is typed at the keyboard as a backslash \. In mathematics, nameless functions are usually denoted using the symbol, as in x x+x. In Haskell, the use of the λ symbol for nameless functions comes from the lambda calculus, the theory of functions on which Haskell is based.

13 Why are Lambda's Useful? 1. Lambda expressions can be used to give a formal meaning to functions defined using currying. For example: means

14 2. Lambda expressions can be used to avoid naming functions that are only referenced once. For example: can be simplified to 3. Lambda expressions can be bound to a name (function argument)

15 Case Expressions (1) Pattern matching need not be tied to function definitions; they also work with case expressions. For example: (2) using a case expression and a lambda:

16 (1) Let and Where The let and where clauses are used to create a local scope within a function. For example: (2)

17 Let vs. Where The is an expression, whereas blocks are declarations bound to the context. For example:

18 Sections An operator written between its two arguments can be converted into a curried function written before its two arguments by using parentheses. For example: This convention also allows one of the arguments of the operator to be included in the parentheses. For example: In general, if is an operator then functions of the form ( ), (x ) and ( y) are called sections.

19 Why Are Sections Useful? Useful functions can sometimes be constructed in a simple way using sections. For example: - successor function - reciprocal function - doubling function - halving function Sometimes it is convenient or necessary to pass an operator as a parameter or when stating its type

20 Exercises (1) Consider a function safetail that behaves in the same way as tail, except that safetail maps the empty list to the empty list, whereas tail gives an error in this case. Define safetail using: (a) a conditional expression; (b) guarded equations; (c) pattern matching. Hint: the library function can be used to test if a list is empty.

21 (2) Give three possible definitions for the logical or operator ( ) using pattern matching. (3) Redefine the following version of ( than patterns: ) using conditionals rather (4) Do the same for the following version:

22 Outline Defining Functions List Comprehensions Recursion

23 List Comprehensions A convenient syntax for defining lists Set comprehension - In mathematics, the comprehension notation can be used to construct new sets from old sets. E.g., {(x 2,y 2 ) x {1,2,...,10}, y {1,2,...,10}, x 2 +y 2 101} Same in Haskell: new lists from old lists generates:

List Comprehensions: Generators The expression to generate values for x. generators can be infinite, e.g., is called a generator, as it states how Comprehensions can have multiple generators, separated by commas. For example: Multiple generators are like nested loops, with later generators as more deeply nested loops whose variables change value more frequently. 24

25 For example: x [1,2,3] is the last generator, so the value of the x component of each pair changes most frequently.

26 Dependent Generators Later generators can depend on the variables that are introduced by earlier generators. The list [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)] of all pairs of numbers (x,y) such that x and y are elements of the list [1..3] and y x. Using a dependant generator we can define the library function that concatenates a list of lists:

27 Guards List comprehensions can use guards to restrict the values produced by earlier generators. Shell CSCE 314 TAMU list all numbers x s.t. x is an element of the list [1..10] and x is even Example: Using a guard we can define a function that maps a positive integer to its list of factors:

28 A positive integer is prime if its only factors are 1 and itself. Hence, using factors we can define a function that decides if a number is prime: Shell CSCE 314 TAMU Using a guard we can now define a function that returns the list of all primes up to a given limit:

29 The Zip Function A useful library function is zip, which maps two lists to a list of pairs of their corresponding elements. Using zip we can define a function that returns the list of all positions of a value in a list:

30 Using zip we can define a function that returns the list of all pairs of adjacent elements from a list: Shell CSCE 314 TAMU Using pairs we can define a function that decides if the elements in a list are sorted:

31 Exercises (1) A triple (x,y,z) of positive integers is called pythagorean if x 2 + y 2 = z 2. Using a list comprehension, define a function that maps an integer n to all such triples with components in [1..n]. For example:

32 (2) A positive integer is perfect if it equals the sum of all of its factors, excluding the number itself. Using a list comprehension, define a function that returns the list of all perfect numbers up to a given limit. For example:

33 (3) The scalar product of two lists of integers xs and ys of length n is given by the sum of the products of the corresponding integers: n-1 i = 0 (xs i * ys i ) Using a list comprehension, define a function that returns the scalar product of two lists.