Docsity

Haskell: Mapping, Filtering Lists with Comprehension, Recursion, and HOFs, Study notes of Computer Science

Partial preview of the text

Download Haskell: Mapping, Filtering Lists with Comprehension, Recursion, and HOFs and more Study notes Computer Science in PDF only on Docsity!

Mapping via List Comprehension

More generally, for any functionmultAll m lst = [ mx | x <- lst]multAll :: Int -> [Int] -> [Int]addPairs pairList = [[m+n] | (m,n) <- pairList]addPairs :: [(Int,Int)] -> [[Int]]doubleAll lst = [ 2x | x <- lst] doubleAll :: [Int] -> [Int] Applying a transformation to every element of a list:

(^) f (^) of type (^) a -> b , we can define a

function (^) applyF (^) with type (^) [a] -> [b]

(^) by:

applyF lst = [

(^) f x | x <- lst]

Mapping via Primitive Recursion

More generally, for any functionmultAll m (x:xs) = mx : multAll m xsmultAll m [] = []addPairs ((m,n):rest) = [m+n] : addPairs restaddPairs [] = []doubleAll (x:xs) = 2x : doubleAll xs doubleAll [] = []

(^) f (^) of type (^) a -> b , we can define a

function (^) applyF (^) with type (^) [a] -> [b]

(^) by:

applyF (x:xs) = applyF [] = []

(^) f (^) x : (^) applyF xs

Filtering

For any property expressed as functionhalfPairs pairList = [(m,n) | (m,n) <- pairList, n == 2*m]halfPairs :: [(Int,Int)] -> [(Int,Int)]lessThanTen lst = [ x | x <- lst, x < 10] lessThanTen :: [Int] -> [Int] Filtering elements from a list:

(^) p (^) of type (^) a -> Bool

, we can

define a function

(^) filterP (^) with type (^) [a] -> [a]

(^) by:

filterP lst = [ x | x <- lst,

(^) p x]

filter p lst = [ x | x <- lst, p x] filter :: (a -> Bool) -> [a] -> [a]^ To be even more generic:

Filtering via

filter

isHalfPair (m,n) = isHalfPair :: (Int,Int) -> Bool^ Examples:filter p lst = [ x | x <- lst, p x] filter :: (a -> Bool) -> [a] -> [a]^ Recall:

(^) (n == 2*m)

filter isDigitfilter isHalfPair [(3,7),(4,8),(5,9),(10,21),(11,22)]

(^) [โ€™aโ€™, โ€™3โ€™, โ€™7โ€™, โ€™\nโ€™, โ€™bโ€™, โ€™Zโ€™, โ€™8โ€™]

filter not

(^) [True, False, False, False, True]