wiki:Functions/Filter

Filter

(define filter (lambda (f xs)
                   (cond ((null? xs)  '())
                         ((f (car xs)) (cons (car xs) (filter f (cdr xs))))
                         (else (filter f (cdr xs))))))
(define filter (lambda (f xs)
    (foldr (lambda (x xs) (if (and (not (null? x)) (f x)) (cons x xs) xs)) '() xs)))
filter _pred []    =  []
filter pred (x:xs)
  | pred x         = x : filter pred xs
  | otherwise      = filter pred xs
filter p xs = [ x | x <- xs, p x]
filter p  =  foldr f []
   where
      f x xs
        | p x        =  x : xs
        | otherwise  =  xs
filter(P, [H|T]) ->
    case P(H) of
         true -> [H|filter(P, T)];
         false -> filter(P, T)
    end;
filter(P, []) -> [].

mutual recursion, n-arity helper, pattern-matching

filter(P, []) -> [];
filter(P, [H|T]) -> filter(P(H), H, P, T).

filter(true, H, P, T) -> [H|filter(P, T)];
filter(false, H, P, T) -> filter(P, T).

guarded list comprehension

filter(P, L) when is_function(P, 1) ->
    [E || E <- L, P(E)].
from typing import Callable, Iterable

def filter(fn: Callable, xs: Iterable) -> Iterable:
    return [x for x in xs if fn(x)]

python's generator comprehensions

(item for item in iterable if function(item))
Last modified 4 years ago Last modified on Feb 25, 2017, 1:49:36 PM
Note: See TracWiki for help on using the wiki.