CS 222

Logo

Programming Languages

Haskell Activity 3

Open the comand prompt / terminal, navigate to your desktop, and enter ghci. Open a code editor (e.g., Atom, Visual Studio Code, Sublime Text) and create a file activity03.hs; save it to the cs222 folder on your desktop. As you write functions, test them in ghci.

It is expected that you have read Ch. 3 of your Haskell book.

Experiment with lists in ghci

  1. In ghci, enter each of the following expressions and press enter. Obseve the output. What does each expression do?
    • [1,2,3,4]
    • 1 : (2: (3: (4: [ ] )))
    • [1..4]
    • [1..] Note: you’ll want to use ctrl + c.
    • [ 'h', 'e', 'l', 'l', 'o' ]
    • 'h' : ('i' : [ ] )
    • ['a'..'z']
    • [5,8..32]
    • head ['a'..'z']
    • tail ['a'..'z']
    • head [1,2,3,4]
    • tail [1,2,3,4]
    • length [1,2,3,4]
    • head [ 1 ]
    • tail [ 1 ]
  2. Use sum (which takes a list) to get the sum of the first 100 numbers.

  3. Use product (which takes a list) to obtain the factorial of 10.

  4. Practice using each of the functions in Fig. 2 on pg 21 of your book. Mind the function declarations.

  5. In ghci, enter the following invalid expressions. Why do they produce an error?
    • head [ ]
    • tail [ ]
    • tail (head [1..100]) (hint: try to evaluate the argument to tail)
  6. Observe the lazy evaluation strategy by evaluating the expression [1..n] for increasing values of n (say, n is 1000, 10000, 100000, 10000000). For example, type [1..100000] and press enter.
    • Now try head [1..n] for increasing values of n. Does it take just as long as you’d expect?
    • Now try tail [1..n] for increasing values of n. How long does it take for large values of n?
    • Lastly, try head (tail [1..n]) for large values of n. What happens, in terms of the amount of time it takes to compute?

In activity03.hs file

  1. Add the following polymorphic function to your file, save, and test it with an input list of at least two elements. What does it do? Write in comments above
    revHead ls = (head (tail ls)) : ((head ls) : (tail (tail ls)))
    
  2. Write a polymorphic function called addL which takes three lists and concatenates them into one list containing all items.

  3. Write a polymorphic function called firstLast which takes a list and removes the first element and the last element. It should display an error message if the list is too small (1 item or less) but should otherwise work.

  4. Write a function called strip n ls that returns the argument list ls with the first n and last n elements removed.

How to submit

Submit your file to Moodle which has all function definitions.