Category: Uncategorized

  • Exercise 5.4

    Assume that f2 = map. Then: f1 :: [a -> a] -> a -> [a] f1 fs x = map (\f -> f x) fs Or in one line: (\fs x -> map (\f -> f x) fs) (map (*) [1,2,3,4]) 5 => [5,10,15,20]

  • Exercise 5.3

    Note: Anonymous functions are not introduced until chapter 9! But they are an easy way to solve problems like this. mylength :: [a] -> Int mylength xs = foldl (\x _ -> x + 1) 0 xs

  • Exercise 5.2

    map map [x] = [map x] Therefore: x :: a -> b because x is the first argument to map. Consider the type of map: map :: (a -> b) -> [a] -> [b] This implies: map x :: [a] -> [b] [map x] :: [[a] -> [b]] And hence: map map :: [a -> […]

  • Exercise 5.1

    Recall the definitions from Exercise 2.3. area’ :: Shape -> Float area’ (Polygon (v1:vs)) = let arealist = map (\(v2, v3) -> triArea v1 v2 v3) (zip vs (tail vs)) in foldl (+) 0 arealist (zip vs (tail vs)) turns out to be a handy idiom.

  • Exercise 4.2

    From the text: intToFloat :: Int -> Float intToFloat i = fromInteger (toInteger i) The exercise: pixelToInch :: Int -> Float pixelToInch x = intToFloat x / 100 {- pixelToInchBad :: Int -> Float pixelToInchBad x = intToFloat (x / 100) -} pixelToInchBad :: Int -> Float pixelToInchBad x = intToFloat (x `div` 100) Apart […]

  • Exercise 4.1

    inchToPixel :: Float -> Int inchToPixel x = round (100 * x) inchToPixelBad :: Float -> Int inchToPixelBad x = 100 * round x The second definition is bad because rounding a small floating point number leads to a loss of precision in the integer. Better to multiply by 100 first, before rounding. For example, […]

  • Exercise 3.2

    From the text: spaceClose :: Window -> IO () spaceClose w = do k Int mulcos30 n = n * 86603 `div` 100000 equiTri :: Color -> Window -> Int -> Int -> Int -> Int -> IO () equiTri color w x y yorient size = let halfsize = size `div` 2 height = […]

  • Exercise 3.1

    myPutStr :: String -> IO () myPutStr [] = return () myPutStr (c : cs) = do putChar c myPutStr cs myGetLine :: IO String myGetLine = do c

  • Exercise 2.5

    {- Area of a shape: compute by adding up the trapezoidal areas formed by pair of vertices with the x-axis. This can (correctly) be negative when x2 > x1. -} axisTrapezoidArea :: Vertex -> Vertex -> Float axisTrapezoidArea (x1, y1) (x2, y2) = (x1 – x2) * (y1 + y2) * 0.5 area :: Shape […]

  • Exercise 2.4

    {- Is a shape convex: compute the cross product of the two vectors formed by each 3 vertices – a convex shape will have all the cross products the same sign. -} crossProduct :: Vertex -> Vertex -> Vertex -> Float crossProduct (x1, y1) (x2, y2) (x3, y3) = (x2 – x1) * (y3 – […]