;; ;; FILE: list-operations-fp.rkt ;; AUTHOR: Eugene Wallingford ;; DATE: 2024/02/14 ;; COMMENT: This file gives functional implementations of list-length ;; and list-member?. ;; #lang racket ;; -------------------------------------------------------------------- ;; How can we write list-length without recursion? ;; -------------------------------------------------------------------- ;; Our function list-length will receive a list, lst. For now, let's ;; define a list for thinking out loud. (define lst '(a s d f g h j k l)) ;; How much does each item contribute to the length of the list? ;; Exactly one. Here is a way to get a list of the "1 counts": (map (lambda (symbol) 1) lst) ;; This gives (1 1 1 1 1 1 1 1 1). If we add up all the 1s, we will ;; know the length of the list. apply to the rescue: (apply + (map (lambda (symbol) 1) lst)) ;; So there's the body of our function! (define list-length (lambda (lst) (apply + (map (lambda (symbol) 1) lst)))) (list-length lst) ;; -------------------------------------------------------------------- ;; How can we write list-member? without recursion? ;; -------------------------------------------------------------------- ;; Now let's try to do the same sort of thing for our list-member? function. ;; It will receive a number, n, and a list, lon. For now, let's define some ;; values with which we can use to think out loud. (define n 4) (define lon '(1 2 3 4 5 6 7 8)) ;; This is one way to apply an equality test to every item in the ;; list, to see if the item is equal to n: (map (lambda (m) (= n m)) lon) ;; This gives (#f #f #f #t #f #f #f #f). See the #t in the middle? ;; If only we could (apply or ...) to the result, we would be done: ;; (apply or ;; (map (lambda (m) ;; (= n m)) ;; lon)) ;; But or is a special form, not a function. [Given what you know ;; from other programming languages, why do you imagine that is?] ;; ;; That's okay. Racket provides a function *ormap* that computes ;; (apply or (map ...)) (define list-member? (lambda (n lon) (ormap (lambda (m) (= n m)) lon))) (list-member? n lon) ;; Can we write any-bigger-than? without using recursion? ;; Sure: All we have to do is change the '= in list-member? to a '< ! ;; ;; This is another example of how we can factor a function out of a ;; larger computation to create a more general tool. ;; ;; (If I were in charge of Racket, I would call ormap "any?".) ;; ;; --------------------------------------------------------------------