Use scheme programming please Problem8 Recall that the function fold-left takes
ID: 667709 • Letter: U
Question
Use scheme programming please
Problem8 Recall that the function fold-left takes a function f, initial value j, a list (e1, e2... en) It returns a left-parenihesization of the applications of f to list elements, starting from (f i ci). Its dual is called fold-right, which is the right-parenthesization version of fold-left, starting from (f i en. Define the following functions in Scheme using fold-left or fold-right. You cannot use the equivalent functions (i.e., length. map. filter) in Scheme. a) (5pt) Define a function length h. which takes a list and return the length of the list. For example. Length h(1 2.34)=4. b) (5pt) Define a function mapp which implements map. (implement the simple case only, where mapp take just one function and one list.) c) (5pt) Define a function filter which implements filter.Explanation / Answer
;; computes the length of a list (define (my-length l) (if (null? l) 0 (+ 1 (my-length (cdr l))))) //map does this (map f (a_0 a_1 ... a_n)) = ((f a_0) (f a_1) ... (f a_n)) (define (my-map f l) (if (null? l) '() (cons (f (car l)) (my-map f (cdr l))))) (define (square-each l) (my-map square l)) ;;; the next functions are fold-left and fold right, which we will first define mathematically ;;; define (fold-left f t_0 l) = t_n ;;; define (fold-right g s_0 l) = s_n (define (fold-right g s l) (if (null? l) s (g (car l) (fold-right g s (cdr l))))) (define (fold-left f t l) (if (null? l) t (fold-left f (f t (car l)) (cdr l)))) ;;; filter is a very hip higher order function ;;; kicks out anything not satisfying pred (define (filter pred lst) (fold-right (lambda (x m) (if (pred x) (cons x m) m)) '() lst))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.