Functional Problem Solving (CSC 151 2015F) : EBoards

CSC151.01 2015F, Class 2^5: Naming Local Procedures


Overview

Preliminaries

Admin

Upcoming Work

Extra Credit Opportunities

Academic

Peer Support

Upcoming Peer Support

Other Good Stuff to Do

Questions

Some Incorrect Implementations of iota

A typical start

(define my-iota
  (lambda (n)
    (if (zero? n)
        null
        (cons (- n 1) (my-iota (- n 1))))))

Problem. It's backwards! Here's an incorrect approach to fixing the problem.

(define my-iota
  (lambda (n)
    (if (zero? n)
        null
        (cons (- n 1) (reverse (my-iota (- n 1)))))))

What happens?

(my-iota 1) => '(0)
(my-iota 2) => (cons 1 (reverse '(0))) => '(1 0)
(my-iota 3) => (cons 2 (reverse '(1 0))) => '(2 0 1)
(my-iota 3) => (cons 3 (reverse '(2 0 1))) => '(3 1 0 2)

Maybe reverse is in the wrong place

(define my-iota
  (lambda (n)
    (if (zero? n)
        null
        (reverse (cons (- n 1) (my-iota (- n 1)))))))

(my-iota 1) => '(0)
(my-iota 2) => (reverse (cons 1 '(0))) => (reverse '(1 0)) => '(0 1)
(my-iota 3) => (reverse (cons 2 '(0 1))) => (reverse '(2 0 1)) => '(1 0 2)

Lab

You can use all and any to check a predicate on every member of a list

    > (all irgb? (list "a" "b" "c"))
    #f

    > (all irgb? (list (irgb 1 1 1)))
    #t

let vs letrec (aka Sam is evil)

(define colonel
  (lambda (vals largest-so-far)
    0))

(define largest
  (lambda (vals)
    (let ([colonel (lambda (vals largest-so-far)
                     (if (null? vals)
                         largest-so-far
                         (colonel (cdr vals) 
                                  (max (car vals) largest-so-far))))])
      (colonel (cdr vals) (car vals)))))

Exercise: 4 a/b