Assignment 2: Haskell II

    1. In a file Pairs.hs, define a module Pairs exporting two functions, pairMap and withBoth. Include type declarations for both functions.

    • pairMap takes a function and a pair, applies the function to each element of the pair, and returns the results in a new pair.

        • *Pairs> pairMap (+1) (2,3)

        • (3,4)

    • withBoth takes a "two-argument" function and a pair and returns the result of applying the function to both values.

        • *Pairs> withBoth (+) (2,3)

        • 5

    1. In a file Tree.hs, define a data type Tree that represents a general (not necessarily binary) tree. A Tree is either a Leaf with a value or a Node with a value and a list of children (themselves Trees). Use record syntax so that arguments to value constructors can optionally be specified out of order. Make your type an instance of the typeclasses Show and Functor. Your definition of show should return a nicely indented "book index" style string representing the tree.

      1. *Main> let example = Node 1 [Node 5 [Leaf 6, Leaf 7], Node {children=[Leaf 4], value=3}] *Main> example 1 5 6 7 3 4 *Main> fmap (2*) example 2 10 12 14 6 8

    1. In a file Counts.hs, write a program to solve the sorted word frequency problem described in this blog post. Your implementation should be case-sensitive (e.g., "The" is not the same as "the"); it's easier that way. Include type declarations for any functions other than main. Separate computation from I/O as much as possible.

    2. Here it finds the 10 most common words in Moby Dick (which takes a few seconds):

      1. bash-3.2$ runhaskell Counts 10 < moby.txt

      2. the:13549

      3. of:6381

      4. and:5865

      5. a:4460

      6. to:4391

      7. in:3774

      8. that:2672

      9. his:2404

      10. I:1746

      11. with:1618

    3. In a Google word processing document lingo2, show the "Hello, world!" program in your pet language. While it is fine if you found this code on line (give a source), you must have actually run the program. You must therefore have found a compiler or interpreter for your language. Explain which one you used, where you got it, and any difficulties you experienced setting it up. Installing software (especially if it is experimental) can be a frustrating and time-consuming process; start early!

Hints

    • The Pairs functions are very short -- one line each.

    • A recursive helper function is useful for the show function in the Tree problem.

    • The instance lines for the two typeclasses for Tree should be instance (Show a) => Show (Tree a) where and instance Functor Tree where.

    • In my version of Counts, I imported Data.List, System.Environment, and (qualified as Map) Data.Map.

    • Some functions that I found handy in Counts: take, words, Map.lookup, sortBy, compare. Your solution may vary.

What to Hand In

  • Pairs.hs

  • Tree.hs

  • Counts.hs

  • lingo2