Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhyrexTsai/c5aca6b3ac7190c2b63c389db70bdb1a to your computer and use it in GitHub Desktop.
Save PhyrexTsai/c5aca6b3ac7190c2b63c389db70bdb1a to your computer and use it in GitHub Desktop.
Higher-order functions and list comprehension.md
compre :: [a] -> (a->b) -> (a->Bool) -> [b]
compre xs f p = [ map (f x) | x <- xs, filter p xs ]
main = do
print(compre [2,4,5,8,12] (*3) (\x -> x>=3 && x<=10))
compre :: [a]->(a->b)->(a->Bool)->[b]
compre xs f p = map f $ filter p xs
main = do
print(compre [2,4,5,8,12] (*3) (\x -> x>=3 && x<=10))

Higher-order functions and list comprehension

a. Study the code fragment below and identify the operation it provides. Then rewrite it using map and filter, and name it as q1f1a.

q1f1 :: [Int] -> [Int]
q1f1 [] = []
q1f1 (x:xs) | x < 3	= q1f1 xs
            | x > 10	= q1f1 xs
            | otherwise   = x*3 : q1f1 xs

b. Now rewrite q1f1 using list comprehensions and name it as q1f1b. c. Express the comprehension

[f x | x <- xs, p x]

as a function using the functions map and filter. Call the function compre:

compre :: [a]->(a->b)->(a->Bool)->[b]
compre xs f p = … --using map and filter
q1f1a :: [Int] -> [Int]
q1f1a [] = []
q1f1a xs = map (*3) $ filter (\x -> x>=3 && x<=10) xs
main = do
print(q1f1a [2,4,5,12])
q1f1a :: [Int] -> [Int]
q1f1a [] = []
q1f1a xs = map (*3) $ filter (>=3) $ filter (<=10) xs
main = do
print(q1f1a [2,4,5,12])
q1f1b :: [Int] -> [Int]
q1f1b [] = []
q1f1b xs = [ x*3 | x <- (filter (\x -> x>=3 && x<=10) xs)]
main = do
print(q1f1b [2,4,5,12])
q1f1b :: [Int] -> [Int]
q1f1b [] = []
q1f1b lt = [(*3) elem | elem <- lt, elem>=3, elem<=10]
main = do
print(q1f1b [2,4,5,12])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment