Haskell - PowerPoint PPT Presentation

1 / 11
About This Presentation
Title:

Haskell

Description:

Take. Two base cases (n=0, or empty list) Guard without otherwise will fall through to patterns. take' :: (Num i, Ord i) = i - [a] - [a] take' n _ – PowerPoint PPT presentation

Number of Views:91
Avg rating:3.0/5.0
Slides: 12
Provided by: minesEdu
Category:
Tags: haskell

less

Transcript and Presenter's Notes

Title: Haskell


1
Haskell
  • Chapter 4

2
Recursion
  • Like other languages
  • Base case
  • Recursive call
  • Author programs a number of built-in functions as
    examples
  • Quick
  • maximum 3,5,4 gt 5 Whats the base case?
  • replicate 4 3 gt 3,3,3,3 Whats the base case?
  • take 3 1..10 gt 1,2,3 Whats the base case?
  • take 5 1..3 gt 1,2,3 Whats the base case?

3
Maximum
  • maximum' (Ord a) gt a -gt a
  • maximum' error "can't take maximum of empty
    list
  • -- base case, if only one item, return it
  • maximum' x x
  • -- else return max of first element or recursive
    call
  • maximum' (xxs) max x (maximum' xs)

4
Replicate
  • replicate' Int -gt a -gt a
  • replicate' n x
  • -- base case returns empty list
  • n lt 0
  • -- else cons element to result of recursive call
  • otherwise x replicate' (n-1) x
  • Used guards because boolean condition, not a
    pattern
  • replicate' 3 5
  • 5 replicate 2 5 gt 5,5,5
  • 5 replicate 1 5 gt 5, 5
  • 5 replicate 0 5 gt 5
  • n 0, gt

5
Take
  • Two base cases (n0, or empty list)
  • Guard without otherwise will fall through to
    patterns
  • take' (Num i, Ord i) gt i -gt a -gt a
  • take' n _
  • n lt 0
  • take' _
  • take' n (xxs) x take' (n-1) xs

Quick trace (turn in) take' 20 1..10 take' 3
1..10
6
Reverse
  • Note rather than because both are lists
  • works at front of list, not back
  • reverse' a -gt a
  • reverse'
  • reverse' (xxs) reverse' xs x

7
Repeat
  • Haskell supports infinite lists
  • repeat' a -gt a
  • repeat' x xrepeat' x
  • repeat 3
  • 3 repeat 3
  • 3 repeat 3
  • etc,

8
Think it through dont look ahead!
  • Preludegt zip 1,2,3 4,5,6
  • (1,4),(2,5),(3,6)
  • How would you write zip?
  • How many base cases?
  • Whats the recursive call?
  • Patterns or guards?
  • give patterns a try!

Add to your class participation
9
Zip
  • zip' a -gt b -gt (a,b)
  • zip' _
  • zip' _
  • zip' (xxs) (yys) (x,y)zip' xs ys

10
Quick Exercise
  • With a partner, trace this code with this list of
    numbers
  • 5,2,6,7,1,3,9,4
  • quicksort (Ord a) gt a -gt a
  • quicksort
  • quicksort (xxs)
  • let
  • smallerOrEqual a a lt- xs, a lt x
  • larger a a lt- xs, a gt x
  • in quicksort smallerOrEqual x quicksort
    larger

Turn in for class participation credit
11
Play and Share?
  • No, lets start on the homework.
Write a Comment
User Comments (0)
About PowerShow.com