This is an old revision of the document!


6. Functional closures

Function application and composition as higher-order functions

One key idea from functional programming is that functions are first-class (or first-order) values, just like integers, strings, etc. . They can be passed as function arguments and also be returned by function application.

Functions which take other functions as parameter are called higher-order.

Lambdas

46. Functions can be passed as arguments just like any other value value. Also, functions can be returned as parameter. In order to do so, it is convenient to define functions without naming them. This is done using lambda's. For a more detailed discussion regarding lambdas, see the lecture. The following definitions are equivalent:

f x y = x + y 
f x = \y -> x + y
f = \x -> \y -> x + y
f = \x y -> x + y

6.1. Warm-up

Consider an URL such as: domain-name.com/books/get_item?param1=1234&param2=5678. In the previous example:

  • books is a resource-name
  • get_item is an action
  • param1 and param2 are parameters with associated values 1234 and 5678 respectively.

6.1.1. Write the following functions:

  • get_resource
  • get_action
  • get_params

which extract the resource name, the action and the parameters of a given URL (represented as string). Write yourself the signature of the functions. When implementing, try to:

  • generalise as much as possible
  • use higher-order functions and composition

6.1.2. Given a list of URLs, extract those which satisfy, at the same time the following constraints:

  • have the domain name equal to “gmail.com” or “yahoo.com”
  • have the resource equal to “books” or “movies”
  • have an action from the set {get_item, remove_item, insert_item}
  • have at least three parameters

Choose the most effective way of writing your code such that:

  • your code is easy to use
  • your code is easy to extend

2.1. Consider sets represented as characteristic functions with signature s :: Integer → Bool, where s x is true if x a member in the set. Examples:

s1 1 = True
s1 2 = True
s1 _ = False
 
s2 x = mod x 2 == 0
 
s3 _ = False

Above, s1 is the set $ \{1,2\}$ , s2 is the set of even integers and s3 is the empty-set. Write a function which tests if an element is a member of a set:

mem :: (Integer -> Bool) -> Integer -> Bool
mem = ...

2.2. Define the set $ \{2^n \mid n\in\mathbb{N}\}$ .

2.3. Define the set of natural numbers.

2.4. Implement the intersection of two sets. Use lambdas.

intersection :: (Integer -> Bool) -> (Integer -> Bool) -> (Integer -> Bool)

2.5. Write intersection in another way, (without using lambdas).

intersection' :: (Integer -> Bool) -> (Integer -> Bool) -> Integer -> Bool

2.6. Write a function which takes a list of integers, and returns the set which contains them.

toSet :: [Integer] -> (Integer -> Bool)

2.7. Implement a function which takes a list of sets and computes their intersection.

capList :: [Integer -> Bool] -> Integer -> Bool