Lab: Haskell Babbling
In today's lab, you'll get what is likely your first experience writing Haskell. You won't write standalone programs but just utility functions. Functions in Haskell aren't a series of statements. They are just a single expression that produces a value. That expression can contain conditional logic, function calls, and references to local variables.
Tasks
Get acquainted with Haskell's syntax, type system, and standard library by completing the following tasks:
Create a file named
babbling.hs. Test the functions that you write using ghci and the :load command.
Write a function
dollarize that accepts an integer number of cents and returns a string showing the amount in dollars. For example:
-
dollarize 68→"$0.68" -
dollarize 98765→"$987.65" -
dollarize 3406→"$34.06"
show function, and a conditional statement to pad out the number of cents. Use a where clause to store intermediate results instead of jamming everything into one expression.
One interesting feature of Haskell is Hoogle, which lets you search for functions by their type signature. Let's use Hoogle in a little game called Function Composition that plays like this:
- Write down four types, real or wildcard, in a comment.
-
Use Hoogle to find three single-parameter functions that will stitch together to bring from you from the first type to the last. The value returned by the first function will be passed along to the second function, and so on. Some functions indexed by Hoogle require extra libraries that you probably don't have installed. Avoid these by confining the search to
package:baseorset:included-with-ghc. -
Define a function
chainP. Have it call the three functions, and use parentheses to associate. -
Define a function
chainD. Have it call the three functions, and use$to associate.
Write a function
abbreviate that turns a long word into a trendy numeric abbreviation. For example:
-
abbreviate "internationalization"→"i18n" -
abbreviate "hamburger"→"h7r" -
abbreviate "lot"→"lot" -
abbreviate "loot"→"l2t"
Write a function
quadrant that accepts a Cartesian coordinate pair of numbers. It returns "I", "II", "III", or "IV" to indicate the pair's quadrant. If the pair doesn't lie in a quadrant, it returns "?". For example:
-
quadrant (1, 2)→"I" -
quadrant (0, 0)→"?" -
quadrant (-5, 0)→"?" -
quadrant (3, -10)→"IV"
Write a function
parsePair that accepts a string of the format LABEL: (A, B) or just plain (A, B) and returns A and B as a pair of integers. Include a type signature. Assume LABEL is an arbitrary string. For example:
-
parsePair "Origin: (0, 0)"→(0, 0) -
parsePair "location: (-10, -3)"→(-10, -3) -
parsePair "p: (935, -18)"→(935, -18)
read, drop, elemIndex, and fromMaybe. Use a where clause to store intermediate results.Submit
To receive credit for this lab, you must submit your .hs scripts on Canvas by Monday noon. Late labs or forgot-to-submits are not accepted because Monday at noon is when your instructor has time to grade.