-- ASSIGNMENT #2 SOLUTIONS -- Problem #1 -- Keep all two-tuples from the input list whose elements sum to zero tuplesSummingToZero lst = [ (n,m) | (n,m) <- lst, (n+m) == 0 ] -- Problem #2 -- Find the average distance from the origin to all points in -- the first quadrant (x,y positive). averageDist lst = (sum distances) / fromIntegral(length distances) where distances = [ sqrt (x*x + y*y) | (x,y)<-lst, x>0, y>0 ] -- Problem #3, parts 1 and 2 -- Here are two different ways to compute the area of a "slice". -- The areaRect appraoch approximates the area of the slice with -- a trapezoid, while areaRect uses a simple rectangle with -- height of y1. areaTrap y1 y2 delta = (y1 + y2) / 2 * delta areaRect y1 y2 delta = y1 * delta -- Problem #4 -- The integrate function takes an approximation method, the -- width of the "slices" to use, the lower and upper bounds for -- the X-coordinate, and a function of one argument to be -- integrated. My solution goes until low and high cross, on the -- assumption that delta is small enough that the extra fraction -- of a slice isn't a big deal. integrate method delta low high fn | low > high = error "Illegal range specification" | high-low < delta = method (fn low) (fn high) (high-low) | otherwise = first + rest where first = method (fn low) (fn (low+delta)) delta rest = integrate method delta (low+delta) high fn -- Problem #5 -- Partial application of integrate has specialized it to use the -- trapezoid rule, and a "slice" width of 0.1. All that's left -- are the bounds and the function trapInt = integrate (areaTrap) 0.1 -- Problem #6: -- Here's one version that breaks it down into lots of smaller -- steps, giving each one a name as part of the where expression. mostFrequent [] = error "Not defined on empty lists" mostFrequent lst = head winners where freqs = map (\item->count item lst) lst largest = foldr1 max freqs winners = filter (\item->(count item lst)==largest) lst count item lst = length (filter (==item) lst) -- Here's a much more compact solution, though it ends up re- -- calculating the frequency with which each item occurs. mostFreq lst = foldr1 (\n m->if (count n lst) > (count m lst) then n else m) lst where count item lst = length (filter (==item) lst)