Created
December 30, 2009 19:47
-
-
Save cprieto/266327 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
- 1. | |
- Using a list comprehension, give an expression that calculates the sum | |
- 1^2 + 2^2 + . . . 100^2 of the first one hundred integer squares. | |
-} | |
sqrsum :: Int -> Int | |
sqrsum n = sum [ x^2 | x <- xs ] | |
where | |
xs = [1..n] | |
{- | |
- 2. | |
- In a similar way to the function length, show how the library function | |
- replicate :: Int -> a -> [a] that produces a list of identical elements can | |
- be defined using a list comprehension. For example: | |
-} | |
repl' :: Int -> a -> [a] | |
repl' n a = [ a | _ <- xs ] | |
where | |
xs = [1..n] | |
{- | |
- 3. | |
- A triple (x, y, z) of positive integers is pythagorean if x^2 + y^2 = z^2. Using | |
- a list comprehension, define a function pyths :: Int -> [(Int, Int, Int)] that | |
- returns the list of all pythagorean triples whose components are at most a | |
- given limit. For example: | |
- pyths 10 | |
- [(3,4,5), (4,3,5), (6,8,10), (8,6,10)] | |
-} | |
pyths :: Int -> [(Int, Int, Int)] | |
pyths n = [ (x, y, z) | x <- xs, y <- xs, z <- xs, x^2 + y^2 == z^2 ] | |
where | |
xs = [1..n] | |
{- | |
- 4. | |
- A positive integer is perfect if it equals the sum of its factors, excluding the | |
- number itself. Using a list comprehension and the function factors, define a | |
- function perfects :: Int -> [Int] that returns the list of all perfect numbers | |
- up to a given limit. For example: | |
- perfects 500 | |
- [6, 28, 496] | |
-} | |
-- maps a positive integer to its list of positive factors | |
factors :: Int -> [Int] | |
factors n = [ x | x <- xs, n `mod` x == 0 ] | |
where | |
xs = [1..n] | |
-- returns a list of perfect integers in a range | |
perfects :: Int -> [Int] | |
perfects n = [ x | x <- xs, sum(init(factors x)) == x ] | |
where | |
xs = [1..n] | |
{- | |
- 5. | |
- Show how the single comprehension [(x , y) | x <- [1, 2, 3], y -> | |
- [4, 5, 6]] with two generators can be re-expressed using two comprehensions | |
- with single generators. Hint: make use of the library function concat | |
- and nest one comprehension within the other. | |
-} | |
concat' :: [(Int, Int)] | |
concat' = concat [[(x,y) | y <- [4,5,6]] | x <- [1,2,3]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome