Objectives

  • get used to pure functional programming
  • practice using streams

Introduction

Pure functional programming means programming with no mutable variables. New values are passed to other functions, possibly recursively. Another key concept is the use of higher-order functions: functions that take other functions as parameters. Streams are collections produced by generator functions; streams may be infinite, but programs can still complete because values are only generated as needed.

Elixir

Work through the Elixir introduction up to (not including) processes with particular attention to the chapters on recursion, enumerables and streams. You may also benefit from this web page.

Lab questions

  1. In your CPS506 GitLab repository working directory, do mix new lab5, then cd to that directory and do all the following there.
  2. Write a function to square its parameter.
  3. Write the obvious (and space in-efficient) version of factorial.
  4. Write a version of factorial that takes constant space (without using any library functions). Hint: use a tail-recursive helper function with an extra parameter.
  5. Explore the Enum package, particularly the functions: map, filter, reduce.
  6. Use the Enum functions and the functions above to square all of the elements of a list; calculate the factorial of all elements of a list.
  7. Write your own versions of map, reduce, and filter, without using libraries. Hint: use patern matching and recursive functions.
  8. Write a function to produce a list of the products of the sublists of a list, for example: lp [[1,3],[4,5],[6,7,8]] would produce [3,20,336]. Hint: use the higher-order functions above.
  9. Use a Enum and ranges to produce a list of the first 10 perfect squares; the first 15; the first 10 even perfect squares.
  10. Use a stream to produce a list of the first 10 perfect squares; the first 15; the first 10 even perfect squares. Note that Enum and Stream have many similar functions.