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
-
In your CPS506 GitLab repository working directory, do
mix new lab5
, thencd
to that directory and do all the following there. - Write a function to square its parameter.
- Write the obvious (and space in-efficient) version of factorial.
- 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.
-
Explore the
Enum
package, particularly the functions: map, filter, reduce. -
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. -
Write your own versions of
map
,reduce
, andfilter
, without using libraries. Hint: use patern matching and recursive functions. -
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. -
Use a
Enum
and ranges to produce a list of the first 10 perfect squares; the first 15; the first 10 even perfect squares. -
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
andStream
have many similar functions.