Functional Problem Solving (CSC 151 2016S) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [FAQ] [Teaching & Learning] [Grading] [Taking Notes] [Rubric]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Labs] [Outlines] [Readings] - [Examples] [Handouts]
Reference: [Setup] [Remote] [VM] [Errors] - [Functions A-Z] [Functions By Topic] - [Racket] [Scheme Report (R5RS)] [R6RS] [TSPL4]
Related Courses: [Curtsinger (2016S)] [Davis (2013F)] [Rebelsky (2015F)] [Weinman (2014F)]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Issue Tracker (Course)]
Overview
The primary components of an algorithm
let or definelambda or section or compose let and define and let*let are done before the body.let* are done in order.(compose square increment), increments and then squares.if, and, cond, or,*, modulo, quotient, irgb, ...Improve the algorithm: If there are no books, use a count of 0
(define count
(lambda (lst)
(if (null? lst)
0
(+ 1 (count (cdr lst))))))
or
(define count
(lambda (lst)
(if (null? lst)
0
(increment (count (cdr lst))))))
Goal: Find alphabetically first book by title
Assistant
..
When you have only one book, you know that it's the lightest
;;; Precondition:
;;; lst is nonempty
(define alphabetically-first
(lambda (lst)
; If there's only one element
(if (null? (cdr lst))
; That element is alphabetically first
(car lst)
; Take the rest of the list
; Find the alphabetically first
; Take the first of the two
(let ([guess (alphabetically-first (cdr lst))])
(if (string<=? guess (car lst))
guess
(car lst)))
Revised code
(define alphabetically-first
(lambda (lst)
; If there's only one element
(if (null? (cdr lst))
; That element is alphabetically first
(car lst)
; Take the rest of the list
; Find the alphabetically first
; Take the first of the two
(let ([mine (car lst)]
[guess (alphabetically-first (cdr lst))])
(if (string<=? guess mine)
guess
mine)))))