PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Similar documents
PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

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

Shell CSCE 314 TAMU. Haskell Functions

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

INTRODUCTION TO FUNCTIONAL PROGRAMMING

CSCE 314 Programming Languages

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

Haskell Scripts. Yan Huang

CSCE 314 Programming Languages

A general introduction to Functional Programming using Haskell

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

An introduction introduction to functional functional programming programming using usin Haskell

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

Introduction. chapter Functions

Haskell through HUGS THE BASICS

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

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Lecture 19: Functions, Types and Data Structures in Haskell

Standard prelude. Appendix A. A.1 Classes

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

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

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

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

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

Programming Language Concepts: Lecture 14

INTRODUCTION TO HASKELL

Introduction to Programming, Aug-Dec 2006

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Shell CSCE 314 TAMU. Functions continued

CS 11 Haskell track: lecture 1

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

CS 320: Concepts of Programming Languages

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

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

SML A F unctional Functional Language Language Lecture 19

Haskell An Introduction

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

Functional Programming in Haskell Part I : Basics

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

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

CS 320: Concepts of Programming Languages

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

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

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

LECTURE 16. Functional Programming

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Lists. Michael P. Fourman. February 2, 2010

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

CSE 3302 Programming Languages Lecture 8: Functional Programming

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

List Functions, and Higher-Order Functions

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Lecture 4: Higher Order Functions

Functional Programming and Haskell

CSC324 Principles of Programming Languages

CS 457/557: Functional Languages

CS 320: Concepts of Programming Languages

Software System Design and Implementation

Lecture 2: List algorithms using recursion and list comprehensions

SOFTWARE ENGINEERING DESIGN I

CSC324 Principles of Programming Languages

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CSc 520. Principles of Programming Languages 11: Haskell Basics

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

Introduction to Functional Programming in Haskell 1 / 56

Programming Languages Fall 2013

CS 360: Programming Languages Lecture 12: More Haskell

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

First Haskell Exercises

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

Functional Programming. Big Picture. Design of Programming Languages

Organization of Programming Languages CS3200/5200N. Lecture 11

Functional Programming I *** Functional Programming and Interactive Theorem Proving. Ulrich Berger Michaelmas Term 2006

Overloading, Type Classes, and Algebraic Datatypes

Logical Methods in... using Haskell Getting Started

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Type Systems, Type Inference, and Polymorphism

Box-and-arrow Diagrams

Higher Order Functions in Haskell

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

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

Haskell 5.1 INTERACTIVE SESSIONS AND THE RUN-TIME SYSTEM

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

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

Chapter 11 :: Functional Languages

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

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

Introduction to Haskell

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

FUNCTIONAL PROGRAMMING 1 HASKELL BASICS

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping

Introduction to Functional Programming in Haskell with the help of Hutton s textbook and 101companies

Logic - CM0845 Introduction to Haskell

Transcription:

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 for teaching and prototyping purposes; Hugs is available on the web from: www.haskell.org/hugs 1

Starting Hugs On a Unix system, Hugs can be started from the % prompt by simply typing hugs: % hugs Hugs 98: Based on the Haskell 98 standard Copyright (c) 1994-2005 --- World Wide Web: http://haskell.org/hugs Report bugs to: hugs-bugs@haskell.org > 2

The Hugs > prompt means that the Hugs system is ready to evaluate an expression. For example: > 2+3*4 14 > (2+3)*4 20 > sqrt (3^2 + 4^2) 5.0 3

The Standard Prelude The library file Prelude.hs provides a large number of standard functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists. Select the first element of a list: > head [1,2,3,4,5] 1 4

Remove the first element from a list: > tail [1,2,3,4,5] [2,3,4,5] Select the nth element of a list: > [1,2,3,4,5]!! 2 3 Select the first n elements of a list: > take 3 [1,2,3,4,5] [1,2,3] 5

Remove the first n elements from a list: > drop 3 [1,2,3,4,5] [4,5] Calculate the length of a list: > length [1,2,3,4,5] 5 Calculate the sum of a list of numbers: > sum [1,2,3,4,5] 15 6

Calculate the product of a list of numbers: > product [1,2,3,4,5] 120 Append two lists: > [1,2,3] ++ [4,5] [1,2,3,4,5] Reverse a list: > reverse [1,2,3,4,5] [5,4,3,2,1] 7

Function Application In mathematics, function application is denoted using parentheses, and multiplication is often denoted using juxtaposition or space. f(a,b) + c d Apply the function f to a and b, and add the result to the product of c and d. 8

In Haskell, function application is denoted using space, and multiplication is denoted using *. f a b + c*d As previously, but in Haskell syntax. 9

Moreover, function application is assumed to have higher priority than all other operators. f a + b Means (f a) + b, rather than f (a + b). 10

Examples Mathematics f(x) f(x,y) f(g(x)) f(x,g(y)) f(x)g(y) Haskell f x f x y f (g x) f x (g y) f x * g y 11

Haskell Scripts As well as the functions in the standard prelude, you can also define your own functions; New functions are defined within a script, a text file comprising a sequence of definitions; By convention, Haskell scripts usually have a.hs suffix on their filename. This is not mandatory, but is useful for identification purposes. 12

My First Script When developing a Haskell script, it is useful to keep two windows open, one running an editor for the script, and the other running Hugs. Start an editor, type in the following two function definitions, and save the script as test.hs: double x = x + x quadruple x = double (double x) 13

Leaving the editor open, in another window start up Hugs with the new script: % hugs test.hs Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used: > quadruple 10 40 > take (double 2) [1,2,3,4,5,6] [1,2,3,4] 14

Leaving Hugs open, return to the editor, add the following two definitions, and resave: factorial n = product [1..n] average ns = sum ns `div` length ns Note: div is enclosed in back quotes, not forward; x `f` y is just syntactic sugar for f x y. 15

Hugs does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used: > :reload Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3 16

Naming Requirements Function and argument names must begin with a lower-case letter. For example: myfun fun1 arg_2 x By convention, list arguments usually have an s suffix on their name. For example: xs ns nss 17

The Layout Rule In a sequence of definitions, each definition must begin in precisely the same column: a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 18

The layout rule avoids the need for explicit syntax to indicate the grouping of definitions. a = b + c where b = 1 c = 2 d = a * 2 means a = b + c where {b = 1; c = 2} d = a * 2 implicit grouping explicit grouping 19

Useful Hugs Commands Command Meaning :load name load script name :reload reload current script :edit name edit script name :edit edit current script :type expr show type of expr :? show all commands :quit quit Hugs 20

Exercises (1) (2) Try out slides 2-8 and 14-17 using Hugs. Fix the syntax errors in the program below, and test your solution using Hugs. N = a div length xs where a = 10 xs = [1,2,3,4,5] 21

(3) Show how the library function last that selects the last element of a list can be defined using the functions introduced in this lecture. (4) Can you think of another possible definition? (5) Similarly, show how the library function init that removes the last element from a list can be defined in two different ways. 22

PROGRAMMING IN HASKELL Chapter 3 - Types and Classes 0

What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: False True 1

Type Errors Applying a function to one or more arguments of the wrong type is called a type error. > 1 + False Error 1 is a number and False is a logical value, but + requires two numbers. 2

Types in Haskell If evaluating an expression e would produce a value of type t, then e has type t, written e :: t Every well formed expression has a type, which can be automatically calculated at compile time using a process called type inference. 3

All type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time. In Hugs, the :type command calculates the type of an expression, without evaluating it: > not False True > :type not False not False :: Bool 4

Basic Types Haskell has a number of basic types, including: Bool Char String Int Integer Float - logical values - single characters - strings of characters - fixed-precision integers - arbitrary-precision integers - floating-point numbers 5

List Types A list is sequence of values of the same type: [False,True,False] :: [Bool] [ a, b, c, d ] :: [Char] In general: [t] is the type of lists with elements of type t. 6

Note: The type of a list says nothing about its length: [False,True] :: [Bool] [False,True,False] :: [Bool] The type of the elements is unrestricted. For example, we can have lists of lists: [[ a ],[ b, c ]] :: [[Char]] 7

Tuple Types A tuple is a sequence of values of different types: (False,True) :: (Bool,Bool) (False, a,true) :: (Bool,Char,Bool) In general: (t1,t2,,tn) is the type of n-tuples whose ith components have type ti for any i in 1 n. 8

Note: The type of a tuple encodes its size: (False,True) :: (Bool,Bool) (False,True,False) :: (Bool,Bool,Bool) The type of the components is unrestricted: ( a,(false, b )) :: (Char,(Bool,Char)) (True,[ a, b ]) :: (Bool,[Char]) 9

Function Types A function is a mapping from values of one type to values of another type: not :: Bool Bool isdigit :: Char Bool In general: t1 t2 is the type of functions that map values of type t1 to values to type t2. 10

Note: The arrow is typed at the keyboard as ->. The argument and result types are unrestricted. For example, functions with multiple arguments or results are possible using lists or tuples: add :: (Int,Int) Int add (x,y) = x+y zeroto zeroto n :: Int [Int] = [0..n] 11

Curried Functions Functions with multiple arguments are also possible by returning functions as results: add add x y = x+y :: Int (Int Int) add takes an integer x and returns a function add x. In turn, this function takes an integer y and returns the result x+y. 12

Note: add and add produce the same final result, but add takes its two arguments at the same time, whereas add takes them one at a time: add :: (Int,Int) Int add :: Int (Int Int) Functions that take their arguments one at a time are called curried functions, celebrating the work of Haskell Curry on such functions. 13

Functions with more than two arguments can be curried by returning nested functions: mult mult x y z = x*y*z :: Int (Int (Int Int)) mult takes an integer x and returns a function mult x, which in turn takes an integer y and returns a function mult x y, which finally takes an integer z and returns the result x*y*z. 14

Why is Currying Useful? Curried functions are more flexible than functions on tuples, because useful functions can often be made by partially applying a curried function. For example: add 1 :: Int Int take 5 :: [Int] [Int] drop 5 :: [Int] [Int] 15

Currying Conventions To avoid excess parentheses when using curried functions, two simple conventions are adopted: The arrow associates to the right. Int Int Int Int Means Int (Int (Int Int)). 16

As a consequence, it is then natural for function application to associate to the left. mult x y z Means ((mult x) y) z. Unless tupling is explicitly required, all functions in Haskell are normally defined in curried form. 17

Polymorphic Functions A function is called polymorphic ( of many forms ) if its type contains one or more type variables. length :: [a] Int for any type a, length takes a list of values of type a and returns an integer. 18

Note: Type variables can be instantiated to different types in different circumstances: > length [False,True] 2 > length [1,2,3,4] 4 a = Bool a = Int Type variables must begin with a lower-case letter, and are usually named a, b, c, etc. 19

Many of the functions defined in the standard prelude are polymorphic. For example: fst :: (a,b) a head :: [a] a take :: Int [a] [a] zip :: [a] [b] [(a,b)] id :: a a 20

Overloaded Functions A polymorphic function is called overloaded if its type contains one or more class constraints. sum :: Num a [a] a for any numeric type a, sum takes a list of values of type a and returns a value of type a. 21

Note: Constrained type variables can be instantiated to any types that satisfy the constraints: > sum [1,2,3] 6 > sum [1.1,2.2,3.3] 6.6 > sum [ a, b, c ] ERROR a = Int a = Float Char is not a numeric type 22

Haskell has a number of type classes, including: Num - Numeric types Eq - Equality types Ord - Ordered types For example: (+) :: Num a a a a (==) :: Eq a a a Bool (<) :: Ord a a a Bool 23

Hints and Tips When defining a new function in Haskell, it is useful to begin by writing down its type; Within a script, it is good practice to state the type of every new function defined; When stating the types of polymorphic functions that use numbers, equality or orderings, take care to include the necessary class constraints. 24

Exercises (1) What are the types of the following values? [ a, b, c ] ( a, b, c ) [(False, 0 ),(True, 1 )] ([False,True],[ 0, 1 ]) [tail,init,reverse] 25

(2) What are the types of the following functions? second xs swap (x,y) pair x y = head (tail xs) = (y,x) = (x,y) double x = x*2 palindrome xs = reverse xs == xs twice f x = f (f x) (3) Check your answers using Hugs. 26

PROGRAMMING IN HASKELL Chapter 4 - Defining Functions 0

Conditional Expressions As in most programming languages, functions can be defined using conditional expressions. abs :: Int Int abs n = if n 0 then n else -n abs takes an integer n and returns n if it is non-negative and -n otherwise. 1

Conditional expressions can be nested: signum :: Int Int signum n = if n < 0 then -1 else if n == 0 then 0 else 1 Note: In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals. 2

Guarded Equations As an alternative to conditionals, functions can also be defined using guarded equations. abs n n 0 = n otherwise = -n As previously, but using guarded equations. 3

Guarded equations can be used to make definitions involving multiple conditions easier to read: signum n n < 0 = -1 n == 0 = 0 otherwise = 1 Note: The catch all condition otherwise is defined in the prelude by otherwise = True. 4

Pattern Matching Many functions have a particularly clear definition using pattern matching on their arguments. not :: Bool Bool not False = True not True = False not maps False to True, and True to False. 5

Functions can often be defined in many different ways using pattern matching. For example (&&) :: Bool Bool Bool True && True = True True && False = False False && True = False False && False = False can be defined more compactly by True && True = True _ && _ = False 6

However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: True && b = b False && _ = False Note: The underscore symbol _ is a wildcard pattern that matches any argument value. 7

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

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. [1,2,3,4] Means 1:(2:(3:(4:[]))). 9

Functions on lists can be defined using x:xs patterns. head :: [a] a head (x:_) = x tail :: [a] [a] tail (_:xs) = xs head and tail map any non-empty list to its first and remaining elements. 10

Note: x:xs patterns only match non-empty lists: > head [] Error x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error: head x:_ = x 11

Integer Patterns As in mathematics, functions on integers can be defined using n+k patterns, where n is an integer variable and k>0 is an integer constant. pred :: Int Int pred (n+1) = n pred maps any positive integer to its predecessor. 12

Note: n+k patterns only match integers k. > pred 0 Error n+k patterns must be parenthesised, because application has priority over +. For example, the following definition gives an error: pred n+1 = n 13

Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. x x+x the nameless function that takes a number x and returns the result x+x. 14

Note: 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. 15

Why Are Lambda's Useful? Lambda expressions can be used to give a formal meaning to functions defined using currying. For example: add x y = x+y means add = x ( y x+y) 16

Lambda expressions are also useful when defining functions that return functions as results. For example: const :: a b a const x _ = x is more naturally defined by const :: a (b a) const x = _ x 17

Lambda expressions can be used to avoid naming functions that are only referenced once. For example: odds n = map f [0..n-1] where f x = x*2 + 1 can be simplified to odds n = map ( x x*2 + 1) [0..n-1] 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: > 1+2 3 > (+) 1 2 3 19

This convention also allows one of the arguments of the operator to be included in the parentheses. For example: > (1+) 2 3 > (+2) 1 3 In general, if is an operator then functions of the form ( ), (x ) and ( y) are called sections. 20

Why Are Sections Useful? Useful functions can sometimes be constructed in a simple way using sections. For example: (1+) (1/) (*2) (/2) - successor function - reciprocation function - doubling function - halving function 21

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 null :: [a] Bool can be used to test if a list is empty. 22

(2) (3) Give three possible definitions for the logical or operator ( ) using pattern matching. Redefine the following version of (&&) using conditionals rather than patterns: True && True = True _ && _ = False (4) Do the same for the following version: True && b = b False && _ = False 23