From 6e278075ec0e1616e1bd839fbd6ff310aaf02f5e Mon Sep 17 00:00:00 2001
From: mm0821
Weitere typische Higher-Order Funktionen für den Umgang mit Listen sind map, filter und flatmap. -Sie sind wie folgt definiert:
; [X Y] (X -> Y) (list-of X) -> (list-of Y) (define (map f xs) (cond [(empty? xs) empty] [(cons? xs) (cons (f (first xs)) (map f (rest xs)))])) ; [X] (X -> Boolean) (list-of X) -> (list-of X) (define (filter f xs) (cond [(empty? xs) empty] [(cons? xs) (if (f (first xs)) (cons (first xs) (filter1 f (rest xs))) (filter f (rest xs)))])) ; [X Y] (X -> (list-of Y)) (list-of X) -> (list-of Y) (define (flatmap f xs) (foldr append empty (map f xs)))
; [X Y] (X -> Y) (list-of X) -> (list-of Y) (define (map f xs) (cond [(empty? xs) empty] [(cons? xs) (cons (f (first xs)) (map f (rest xs)))])) ; [X] (X -> Boolean) (list-of X) -> (list-of X) (define (filter f xs) (cond [(empty? xs) empty] [(cons? xs) (if (f (first xs)) (cons (first xs) (filter f (rest xs))) (filter f (rest xs)))])) ; [X Y] (X -> (list-of Y)) (list-of X) -> (list-of Y) (define (flatmap f xs) (foldr append empty (map f xs)))
Die filter Funktion gibt alle Elemente einer Liste zurück, für die eine boolsche Funktion #true ergibt.
> (filter even? (list 1 2 3 4)) (2 4)