Skip to content

Instantly share code, notes, and snippets.

@PhyrexTsai
Last active April 27, 2016 07:40
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/2fc29d178b2386fe4691cee8216e76a8 to your computer and use it in GitHub Desktop.
Save PhyrexTsai/2fc29d178b2386fe4691cee8216e76a8 to your computer and use it in GitHub Desktop.
List comprehension.md
countNeg :: [Int] -> Int
countNeg lt = sum [1 | elem <- lt, elem<0]
main = do
print(countNeg [-10,3,-5,7,8,-9,-11])

List comprehension

a. Using list comprehensions, define a function, countNeg, for counting the number of negative numbers in a list of numbers.

countNeg :: [Int] ->  Int	 
>countNeg [1, -2, 3, -5] = 2

b. Define $x^n$ using a list comprehension. Name the function as raise:

raise :: Int ->  Int ->  Int  
>raise 2 4= 16

c. Pascal's triangle is a triangle of numbers

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

computed as follows: (1) The first row just contains a 1.

(2) The following rows are computed by adding together adjacent numbers in the row above, and adding a 1 at the beginning and at the end. Write a function, pascal, using list comprehension and ++, which maps a positive integer n to the nth row of Pascal numbers. For example, >pascal 5 = [1, 4, 6, 4, 1]. Hint: define an auxiliary function pairs which construct pairs from two consecutive integers in a list.

pairs :: [Int] -> [(Int, Int)]
pairs lt = do
let x = [0] ++ lt ++ [0]
zip (init x) (tail x)
pascal :: Int -> [Int]
pascal 1 = [1]
pascal n = [a+b | (a,b) <- pairs (pascal (n-1))]
main = do
print(pascal 4)
addZero :: [Int] -> [Int]
addZero xs = [0] ++ xs ++ [0]
pairs :: [Int] -> [(Int, Int)]
pairs x = zip (init x) (tail x)
pascal :: Int -> [Int]
pascal 1 = [1]
pascal n = [x+y | (x,y) <- pairs $ addZero (pascal (n-1))]
main = do
print(pairs $ addZero [1,3,3,1])
print(pascal 4)
raise :: Int -> Int -> Int
raise n k = product [(*n) elem | elem <- take k $ [1, 1 ..]]
main = do
print(raise 2 5)
raise :: Int -> Int -> Int
raise x n = product [x | _ <- [1..n]]
main = do
print $ raise 2 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment