Understanding fold-left and fold-right in a diagram

So, my task is to implement the most basic version of the "map" and "filter" functions in Scheme using fold-left or fold-right. It’s very difficult for me to understand what exactly these functions do. Here is what I have:

(define (myMap f l)
    (fold-left (lamda (f a) (f a)) '() l))

(define (myFilter f l)
    (fold-left f '() l))

At the bottom, I intuitively thought it should be. Apply a filter (say a number? To each element l and put the result in a null list). The top is just completely wrong, but I feel that it is more on the right track. Using any lambda function to apply a function to a number?

Here is an example of the output I'm looking for:

(myMap sqrt '(4 9 16 25)) ; (2 3 4 5)
(myFilter odd? '(1 2 3 4 5)) ; (1 3 5)
+4
source share
3 answers

fold-left fold-right , , , fold-right, fold-left - . , :

#!r6rs
(import (rnrs))

;; helper for R6RS fold-left since argument order is swapped
(define (xcons d a) 
  (cons a d))

(fold-left xcons '() '(1 2 3 4)) ; ==> (4 3 2 1)
(fold-right cons '() '(1 2 3 4)) ; ==> (1 2 3 4)

, xcons, , left-fold . SRFI-1 fold-left equvivalent fold , fold-right:

(import (rnrs base)
        (only (srfi :1) fold fold-left))

(fold cons '() '(1 2 3 4))       ; ==> (4 3 2 1)
(fold-right cons '() '(1 2 3 4)) ; ==> (1 2 3 4)

, . , . , , , , , (, ), .

map filter , , fold-right.

a map , cons . , . cons, .

a filter , cons , , .

, , . .

+6

fold: , "" , , : , ( fold).

, , fold-right "" :

(iterator current-element previous-result) ;; produces: next result

"" . fold-left , .

, map , , "", . , f , . , :

(cons (f current-element) previous-result)

:

(define (myMap f lst)
  (define (iterator current-element previous-result)
    (cons (f current-element) previous-result))
  (fold-rigth iterator '() lst))

, myFilter: , "" , , true, .

- fold-left . .

+1

Folds . , , , , , ,

(fold-left <+> [a,b,c..,n] z) === (n <+> (... <+> (c <+> (b <+> (a <+> z)))...))

,

(define (myMap-lt f lst)
  (fold-left 
    (lambda (elem     ; list element
             accum    ; accumulator so far
             )
         ( ... (f elem)    ; map applies f on each elem
              ... accum    ; accum holds list-of-results-so-far
                   ... )   ; need to extend it with this elem result
       ) 
    '()               ; initial value of the accumulator
    lst))

, ,

(fold-right <+> [a,b,c..,n] z) === (a <+> (b <+> (c <+> (... <+> (n <+> z)...))))

, cons f. (?). reverse.

+1

Source: https://habr.com/ru/post/1608255/


All Articles