Filter
From Distributed Interactive Functional Fiction Programming
Main_Page/Snack Code/Functions as arguments
filter - use 'property' function and a list and return a new list constructed from elements of the old list that have a given property
Haskell:
filter':: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' p (x:xs)
| p x = x : filter' p xs
| otherwise = filter' p xs
-- Example of property function
isEven :: Int -> Bool
isEven n = (n `mod` 2 == 0)
-- Example of using filter':
testFilter = filter' isEven [1,2,3,4]
-- returns [2,4]
Scheme:
(define (filter p ls)
(cond ((null? ls) '())
(else (let ((x (car ls)) (xs (cdr ls)))
(if (p x) (cons x (filter p xs))
(filter p xs))))
))
(define (isEven n)
(zero? (modulo n 2)))
(define testFilter (filter isEven '(1 2 3 4)))
