CS 222

Logo

Programming Languages

Haskell Activity 1

You will need Haskell installed to complete this activity. Create a folder on your desktop called cs222. Open the comand prompt / terminal, navigate to your desktop, and enter ghci.

  1. Open your favorite editor and create a file called activity01.lhs. Save it to the cs222 folder on your desktop.
  2. Copy and paste the following comments and code, which computes factorial of a number, into the file
    This file contains definitions for the factorial function
       
    > fact :: Integer -> Integer
    >
    > fact 0 = 1
    > fact n = n * (fact (n-1))
    
  3. Now, in GHC load the file you saved by typing :l activity01

  4. Test your function by entering fact 3

  5. Write an expression that computes the binomial coefficient . Recall that the formula is: . Use the factorial function to do so. Hint: use div.

  6. Add a definition to your file for a binomial coefficient function called choose. The function should take two integer arguments n and k and return the result of and test it. When you call choose 10 5 you should get 252.

  7. Add a definition to your file for the function choose2 to use the recursive definition .

  8. Add a function fib to your file that takes an integer argument n and returns the sum of the n-1 and n-2 fibonnaci numbers. For arguments 0 and 1, the function returns the value 1. Test it.

  9. Write a function fibcase to your file which computes fibonnaci number using the case expression.

  10. Write a function grade :: Int -> Char which converts a grade in the range from 0-100 to a letter grade using the standard scale (A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: 0-59). Any other argument should return ā€˜Eā€™ for error. Hint: use guarded expressions

  11. Write a function abs2 which determines the absolute value of an integer. Note that when you use a negative number as an argument, you must enclose it as parenthesis. For example, you will use abs2 (-5) to test it.

How to submit

Submit your file to Moodle which has all function definitions.