Ch 6 Misc Exercises

Look for opportunities to use map, filter, fold, and scan. Even if you have a solution without one, spend a minute thinking about it. (It is OK to have solutions that do not use these functions.)

  1. a. early :: (Int, String) -> Bool Give true when the number is even or the string starts with A or B; false otherwise.

     ck1a = and [ early (20,"Cattle"), early  (5,"Banana"),
                  early (1, "Antigone"), not $ early (3,"Fail")]
    

    b. addPosn :: (Num a) => (a,a) -> (a,a) -> (a,a) Add the corresponding x and y coordinates.

     ck1b =
       addPosn (3,4) (8,15) == (11,19)
    
  2. An arithmetic sequence starts with a number and then increases by a constant amount. For example, starting at 5 and increasing by 2 gives [5,7,9,…]. Do the same thing in two dimensions:

     goForever :: (Int,Int) -> (Int,Int) -> [(Int,Int)]
     -- next line is not runnable
     goForever (1,4) (2,-1) == [(1,4),(3,3),(5,2),(7,1),...] -- infinite
    
  3. Check your work by writing a function that returns the first four ordered pairs produced by goForever. Call that function goFour.

      ck3 =
         goFour (1,4) (2,-1) == [(1,4),(3,3),(5,2),(7,1)]
    
  4. (allFours) Now you can produce four coordinates in a given direction: N, S, E, W, NE, NW, SE, SW. In this setup, NW is the direction (-1,1) and E is the direction (1,0). Make a list containing the sequence of points you can reach by going 4 in a row in each of these directions.

     ck4 =
      allFours (5,8) ==
       [[(5,8),(6,8),(7,8),(8,8)],
        [(5,8),(6,9),(7,10),(8,11)],
        [(5,8),(5,9),(5,10),(5,11)],
        [(5,8),(4,9),(3,10),(2,11)],
        [(5,8),(4,8),(3,8),(2,8)],
        [(5,8),(4,7),(3,6),(2,5)],
        [(5,8),(5,7),(5,6),(5,5)],
        [(5,8),(6,7),(7,6),(8,5)]]
    
  5. (scoreMC) Given a String answer key and a String student response input, give 6 points for each correct answer, 2 for each blank (_) and 0 points for each wrong answer. Assume the key and the response are the same length.

     ck5 =
       scoreMC "ABCD" "AX_D" == 14
    
  6. (pigLatin) Read the rules for the made-up language Pig Latin. Change each word in the input into Pig Latin.

     pigLatin ["I","have","a","phone"] == ["Iway","avehay","away","onephay"]
    

    Ignore the problem of correct capitalization.

Notes

  • allFours: If you wrote out eight applications of goFour, go back and find a way that involves the human doing less work and the computer doing more work.

  • scoreMC: If you made this a recursive function, go back and edit to produce a non-recursive function.

Last modified October 9, 2023: Chapter six reworked, added notes. (14cd5ab)