Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Gabe Schoenbach
- -- | A module for doing arithmetic with lists.
- module Homework where
- import Prelude hiding (product)
- -- Exercise 2.1
- sumf (sumf square) [[1,2],[3,4]]
- sumf square [1,2] + sumf sumf square [3,4]
- square 1 + sumf square 2 + sumf square 3 + sumf sumf square 4
- 1 + square 2 + sumf square [] + square 3 + sumf square [] + sumf square 4 + sumf sumf square []
- 1 + 4 + 0 + 9 + 0 + square 4 + sumf square [] + sumf square [] + sumf sumf square []
- 14 + 16 + 0 + 0 + 0
- 30
- -- Exercise 2.2
- -- | Compute the product of the numbers in a list
- product :: Num n => [n] -> n
- product [] = 1
- product (c:cs) = c * product cs
- -- | Square a number
- square :: Num n => n -> n
- square x = x^2
- -- | Determine the product of squares of a list
- productSquares :: [Integer] -> Integer
- productSquares = product . map square
- -- productSquares [1..10] = 13168189440000
- -- Exercise 2.3
- -- | Determine if a number n is divisible by d
- divisibleBy :: Integral n => n -> n -> Bool
- divisibleBy d n
- | n `mod` d == 0 = True
- | otherwise = False
- -- | Given a list of predicates ps and a value x, output True iff p x is True for all p in ps
- allp :: [x -> Bool] -> x -> Bool
- allp [] x = True
- allp (p:ps) x
- | p x = allp ps x
- | otherwise = False
- -- | Given a list of predicates ps and a list of values, filter the list down to only the
- -- values that satisfy every predicate
- filterAll :: [x -> Bool] -> [x] -> [x]
- filterAll = filter . allp
- -- Compare the results of using different methods to sum numbers.
- result1 :: Integer
- result1 = sum
- . take 100
- . filter (divisibleBy 2)
- . filter (divisibleBy 3)
- . filter (not . divisibleBy 4)
- . filter (not . divisibleBy 9)
- $ [0..]
- -- result1 = 90000
- result2 :: Integer
- result2 = sum
- . take 100
- . filter (allp [ divisibleBy 2
- , divisibleBy 3
- , not . divisibleBy 4
- , not . divisibleBy 9
- ])
- $ [0..]
- -- result2 = 90000
- result3 :: Integer
- result3 = sum
- . take 100
- . filterAll [ divisibleBy 2
- , divisibleBy 3
- , not . divisibleBy 4
- , not . divisibleBy 9
- ]
- $ [0..]
- -- result3 = 90000
- -- Exercise 2.4 (this is incorrect and unfinished)
- -- | Given a list of predicates and a value x, return True iff p x holds for all x, but define it without recursion.
- -- | Given a predicate and a value, return its truth value.
- eval :: [x -> Bool] -> x -> Bool
- eval p x
- | p x = True
- | otherwise = False
- allP :: [x -> Bool] -> x -> [Bool]
- allP (p:ps) x
- | eval p x : ps
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement