Functional Problem Solving (CSC 151 2015F) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [FAQ] [Teaching & Learning] [Grading] [Taking Notes] [Rubric] [Remote Access]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Labs] [Outlines] [Readings] - [Examples] [Handouts]
Reference: [Setup] [VM] [Errors] - [Functions A-Z] [Functions By Topic] - [Racket] [Scheme Report (R5RS)] [R6RS] [TSPL4]
Related Courses: [Curtsinger (2015F)] [Davis (2013F)] [Rebelsky (2015S)] [Weinman (2014F)]
Misc: [Submit Questions] - [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Issue Tracker (Course)]
Overview
iota.letrec or named let).iotaA 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)
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