Docsity

CS 440: Introduction to Haskell and Recursion - Prof. Alan Mattox Beckman, Study notes of Programming Languages

Toggle sidebar
bg1
CS 440 — Haskell and Recursion January 21, 2008
1 Introduction and Objectives
Welcome to CS 440! In this course you will study programming languages, much in the same way
that a linguist studies human languages. A linguist does not try to learn dozens of spoken (or
dead!) languages. Rather, a linguist studies language families, how words change form and are
combined (grammar and syntax), and how they convey meaning (semantics).
In this lecture we will explain three of the language families that exist, and introduce the host
language, Haskell.
At the end of this lecture you should be able to. . .
•Be able to describe three language families: imperative, object-oriented, functional, and logic.
•Be able to explain the concept of closure and scope.
•Be able to write simple recursive functions over lists and integers, both in direct-style and in
tail recursive style.
2 Language Families
2.1 The Two Questions
1. What is a program?
2. What is data?
Compare these answers for the following paradigms:
•Imperative
•Functional
•Object Oriented
•Logic
3 Introducing Haskell
3.1 Getting Yours
We will use the Glasgow compiler, a.k.a ghc. Go to http://www.haskell.org/ghc/ to download it.
Most Linux package managers will know about this.
3.2 Properties
•Functional
•Lazy
•Strongly Typed
Mattox Beckman Page 1 Illinois Institute of Technology
pf3
pf4
pf5
pf8

Partial preview of the text

Download CS 440: Introduction to Haskell and Recursion - Prof. Alan Mattox Beckman and more Study notes Programming Languages in PDF only on Docsity!

1 Introduction and Objectives

Welcome to CS 440! In this course you will study programming languages, much in the same way that a linguist studies human languages. A linguist does not try to learn dozens of spoken (or dead!) languages. Rather, a linguist studies language families, how words change form and are combined (grammar and syntax), and how they convey meaning (semantics). In this lecture we will explain three of the language families that exist, and introduce the host language, Haskell. At the end of this lecture you should be able to...

  • Be able to describe three language families: imperative, object-oriented, functional, and logic.
  • Be able to explain the concept of closure and scope.
  • Be able to write simple recursive functions over lists and integers, both in direct-style and in tail recursive style.

2 Language Families

2.1 The Two Questions

  1. What is a program?
  2. What is data?

Compare these answers for the following paradigms:

  • Imperative
  • Functional
  • Object Oriented
  • Logic

3 Introducing Haskell

3.1 Getting Yours

We will use the Glasgow compiler, a.k.a ghc. Go to http://www.haskell.org/ghc/ to download it. Most Linux package managers will know about this.

3.2 Properties

  • Functional
  • Lazy
  • Strongly Typed

3.3 Programming in Haskell

Normally, a computer program consists of sentences in the language. By issuing a special directive like // or /* ... */ or rem the text becomes a comment. The compiler ignores it; the human reader probably ignores it too, but we do mean the text to be for them. So, code is the default mode; comments take extra effort. Since it’s easier to write code than comments, most programmers will write more code than comments. Literate programming is a style of programming where the default mode is comment, and by giving a special directive the text can be treated as code. Haskell programs can be in standard mode or literate mode. Standard mode programs use the extension .hs. Comments are delimited using --. Literate mode program files use the extension .lhs. These files can be text files or LATEXfiles. Text files delimit code using >. LATEXfiles delimit code using \begin{code} and \end{code}. In CS 440 we will use LATEXfor official course documents. This document itself is in literate Haskell. You may hand in assignments using any of these three forms.

4 The First Program

The Computer Scientists’ Union requires us to show you how to print the string Hello, world! to the screen whenever we introduce a new language.

1 main = do print "Hello, world!"

To compile it in a Unix environment, use the command ghc.

$ ghc -o hello handout.lhs $ ./hello "Hello, world!" If you leave out the -o hello part, the executable file will be named a.out. There is also an interactive compiler. To use it, run ghci.

$ ghci GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Prelude> :load handout.lhs Ok, modules loaded: Main. Prelude Main> main "Hello, world!" To exit, use control-d. “Prelude” is the name of the standard library module that the Haskell compiler automatically loads. “Main” is the name of the module in our handout.lhs file. It has nothing to do with the fact that we named our starting function main. We will discuss modules in more detail in a future lecture.

5 Scopes and Closures

A scope of a variable is the section of code for which the variable is valid.

7 Recursion over Integers

Recursion is like proof by induction. A proof by induction works by making two steps do the work of an infinite number of steps. It’s really a way of being very lazy!

  • Pick a property P (n) which you’d like to prove for all n.
  • Base case: Prove P (n), for n = 1, or whatever n’s smallest value should be.
  • Induction Case: You want to prove P (n), for some general n. To do that, assume that P (n − 1) is true, and use that information to prove that P (n) has to be true.

The idea is that there are an infinite number of n such that P (n) is true. But with this technique you only had to prove two cases.

Example

To Prove: Let P (n) = “The sum of the first n odd numbers is n^2 .”

Base Case: Let n = 1. Then n^2 = 1, and the sum of the list { 1 } is 1; therefore the base case holds.

Induction Case: Suppose you need to show that this property is true for some n. First, pretend that somebody else already did all the work of proving that P (n − 1) is true. Now use that to show that P (n) is true, and take all the credit.

If { 1 , 3 , 5 ,... , 2 n − 3 } = (n − 1)^2 , then add 2n − 1...

{ 1 , 3 , 5 ,... , 2 n − 3 , 2 n − 1 } = (n − 1)^2 + 2n − 1 ⇒ n^2 − 2 n + 1 + 2n − 1 ⇒ n^2

A recursive routine has a similar structure. You have a base case, a recursive case, and a conditional to check which case is appropriate.

  • Pick a function f (n) which you’d like to compute for all n.
  • Base case: Compute f (n), for n = 1, or whatever n’s smallest value should be.
  • Recursive Case: Assume that someone else already computed f (n − 1) for you. Use that information to compute f (n), and then take all the credit.

Suppose you want a recursive routine that computes the nth square.

1 nthsq 0 = 0 2 nthsq n = 2 ∗ n - 1 + nthsq (n - 1)

*Main> nthsq 8 64

  • The patterns check which case is active.
  • Line 2 is the base case — it stops the recursion.
  • Lines 3 is the recursive case.

Some important things...

  • Your base case has to stop the computation.
  • Your recursive case has to call the function with a smaller argument than the original call.
  • Your if statement has to be able to tell when the base case is reached.
  • Failure to do any of the above will cause an infinite loop.

Activity: Write the factorial function.

8 Recursion over Lists

Linked lists are built into Haskell, and most functional languages.

1 ex3 = [3,4]

*Main> head ex 3 *Main> tail ex [4] *Main> :t ex ex3 :: [Integer]

ex3 3 4

1 ex4 = 3 : 4 : 5 : [] 2 ex5 = [3,4,5]

ex4 3 4 5

1 s = [2,3,4] 2 t = [1,2,3] 3 u = s ++ t

u (^2 3 )

s (^2 3 4) t 1 2 3

Activity 4 Find the tail calls in the calc function below and the fib function.

1 calc 2 i = i 2 calc n i | n ‘mod‘ 2 == 1 = calc (3 ∗ n + 1) (i + 1) 3 | otherwise = calc (n ‘div‘ 2) (i + 1)

  • When you make a function call, you have to save the return address on the stack, so we know where to return.
  • If a call is the last thing done, it is called a tail call. We don’t need to save the stack frame of the function making the tail call in such a case.
  • This optimization can allow recursive programs to run with the same efficiency as imperative programs.

9.2 Direct-Style Recursion

  • In recursion, you split the input into the “first piece” and the “rest of the input”.
  • In direct-style recursion: the recursive call computes the result for the rest of the input, and then the function combines the result with the first piece.
  • In other words, you wait until the recursive call is done to generate your result.

1 sumlist [] = 0 2 sumlist (x:xs) = x + sumlist xs

9.3 Accumulating Recursion

  • In accumulating recursion: generate an intermediate result now, and give that to the recursive call.
  • Usually this requires an auxiliary function.

1 sumlist’ xx = aux xx 0 2 where aux [] a = a 3 aux (x:xs) a = aux xs (a + x)

Activity 5

  1. Write a function that returns the maximum element of a list. Use direct-style recursion. (Assume the list always has at least 1 element.)
  2. Now write the same function, but use tail recursion.
  3. Fix the Fibonacci function to make it run in linear time. Hint: use two accumulators.

10 Further Reading

  • Forward recursion can be made to traverse a list at return time rather than call time, forming a pattern called “There and Back Again,” which can do some interesting things....
  • Example: write a function convolve which takes two lists (x 1 x 2 · · · xn) and (y 1 y 2 · · · yn) and produces an output list (x 1 yn x 2 yn− 2 · · · xny 1 ) where n is unknown. Use only O(n) recursive calls, and no temporary lists.
  • For the solution, see Olivier Danvy’s paper There and Back Again.